import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
import 'dart:typed_data';
import 'dart:ui';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:flutter_progress_hud/flutter_progress_hud.dart';
import 'package:fluttericon/entypo_icons.dart';
import 'package:open_file/open_file.dart';
import 'package:peasmartcare/components/pea_app_bar.dart';
import 'package:peasmartcare/utils/app_util.dart';
import 'package:peasmartcare/widgets/sweetalert/sweetalert.dart';

class FullPhoto extends StatefulWidget {
  final String imageContent;
  final String filename;
  final bool isByteData;

  const FullPhoto({
    Key key,
    @required this.imageContent,
    this.filename,
    this.isByteData,
  }) : super(key: key);
  @override
  _FullPhotoState createState() => _FullPhotoState();
}

class _FullPhotoState extends State<FullPhoto> {
  ReceivePort _port = ReceivePort();
  Uint8List bytes;
  double _downloadProgress = 0;
  String sendPort = "downloader_full_image_send_port";

  @override
  void initState() {
    _bindBackgroundIsolate();
    FlutterDownloader.registerCallback(downloadCallback);
    // bytes = base64.decode(widget.imageBase64);
    super.initState();
  }

  @override
  void dispose() {
    _unbindBackgroundIsolate();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    Size deviceSize = MediaQuery.of(context).size;
    return Scaffold(
      appBar: PEAAppBar(
        title: "รูปภาพ",
        actions: <Widget>[
          // ProfileAvatar(disableEditProfile: true),
        ],
      ),
      body: ProgressHUD(
        child: Builder(
          builder: (context) {
            final progressModal = ProgressHUD.of(context);

            WidgetsBinding.instance.addPostFrameCallback((_) {
              if (_downloadProgress == 100) {
                progressModal.dismiss();
                setState(() {
                  _downloadProgress = 0.0;
                });

                _alertDownloaded(widget.filename);
              }
            });

            Widget imageChild;
            if (widget.isByteData != null && widget.isByteData) {
              Uint8List bytes = base64.decode(widget.imageContent);
              imageChild = Image.memory(
                bytes,
                fit: BoxFit.fitWidth,
              );
            } else {
              imageChild = CachedNetworkImage(
                imageUrl: widget.imageContent,
                progressIndicatorBuilder: (context, url, downloadProgress) => Container(
                  width: 25,
                  height: 25,
                  child: CircularProgressIndicator(
                    value: downloadProgress.progress,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.grey[400]),
                  ),
                ),
                errorWidget: (context, url, error) => Icon(Icons.error),
                fit: BoxFit.fill,
              );
            }
            return Container(
              color: Colors.black,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Expanded(
                    flex: 2,
                    child: Container(
                      height: deviceSize.height - 60,
                      alignment: Alignment.center,
                      child: SingleChildScrollView(
                        child: imageChild,
                      ),
                    ),
                  ),
                  Align(
                    alignment: Alignment.bottomCenter,
                    child: Container(
                      width: double.infinity,
                      height: 60,
                      color: Colors.black,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.end,
                        children: [
                          Container(
                            margin: EdgeInsets.symmetric(horizontal: 10),
                            child: IconButton(
                              icon: Icon(
                                Entypo.download,
                                color: Colors.white,
                              ),
                              onPressed: () async {
                                String localPath = (await AppUtil.getLocalPath()) + Platform.pathSeparator + 'pea_files';

                                final savedDir = Directory(localPath);
                                bool hasExisted = await savedDir.exists();
                                if (!hasExisted) {
                                  savedDir.create();
                                }

                                progressModal.showWithText('กำลังดาวน์โหลด...');

                                await FlutterDownloader.enqueue(
                                  url: widget.imageContent,
                                  fileName: widget.filename != null ? widget.filename : null,
                                  savedDir: localPath,
                                  showNotification: true,
                                  openFileFromNotification: true,
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  )
                ],
              ),
            );
          },
        ),
      ),
    );
  }

  _alertDownloaded(String filename) {
    return SweetAlert.show(
      context,
      subtitle: "ดาวน์โหลดไฟล์สำเร็จ",
      style: SweetAlertStyle.success,
      showCancelButton: true,
      cancelButtonText: "ปิด",
      confirmButtonText: "เปิดไฟล์",
      onPress: (bool isConfirm) {
        if (isConfirm) {
          openFile(filename);
        }

        return true;
      },
    );
  }

  Future<void> openFile(String filename) async {
    print("openFile");
    String localPath = (await AppUtil.getLocalPath()) + Platform.pathSeparator + 'pea_files';

    final result = await OpenFile.open("$localPath/$filename");
  }

  void _bindBackgroundIsolate() {
    bool isSuccess = IsolateNameServer.registerPortWithName(_port.sendPort, sendPort);

    if (!isSuccess) {
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }
    _port.listen((dynamic data) async {
      String id = data[0];
      DownloadTaskStatus status = data[1];
      double progress = data[2] * 1.0;

      print(progress);

      setState(() {
        _downloadProgress = progress;
      });
    });
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping(sendPort);
  }

  static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_full_image_send_port');
    send.send([id, status, progress]);
  }
}
