import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:path_provider/path_provider.dart';
import 'package:quiosco_soler_2/memorias_calculo/pages/interfaz_cuadricula_page.dart';
import 'package:share_plus/share_plus.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:flutter_downloader/flutter_downloader.dart';

class CatalogoGeneral extends StatefulWidget {
  const CatalogoGeneral({Key? key}) : super(key: key);

  @override
  _CatalogoGeneralState createState() => _CatalogoGeneralState();
}

class _CatalogoGeneralState extends State<CatalogoGeneral> {
  final Completer<WebViewController> _controller = Completer<WebViewController>();

  final ReceivePort _port = ReceivePort();
  List<TaskInfo>? _tasks;
  late String _localPath;

  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _bindBackgroundIsolate();
    _prepareSaveDir();

    FlutterDownloader.registerCallback(downloadCallback);
    _isLoading = false;
  }

  void _requestDownload(TaskInfo task) async{
    task.taskId = await FlutterDownloader.enqueue(
      url: task.link!,
      savedDir: _localPath,
      showNotification: true,
      openFileFromNotification: true,
      saveInPublicStorage: true,
    );
  }

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

    if(!isSuccess){
      _unbindBackgroundIsolate();
      _bindBackgroundIsolate();
      return;
    }

    _port.listen((data) {
      String? id = data[0];
      DownloadTaskStatus? status = data [1];
      int? progress = data[2];

      if(progress! >= 100){
        Fluttertoast.showToast(
          msg: "Descarga finalizada.",
          toastLength: Toast.LENGTH_SHORT,
        );
      }

      if(_tasks != null && _tasks!.isNotEmpty){
        final task = _tasks!.firstWhere((task) => task.taskId == id);
        setState(() {
          task.status = status;
          task.progress = progress;
        });
      }
    });
  }

  void _unbindBackgroundIsolate() {
    IsolateNameServer.removePortNameMapping('downloader_send_port');
  }

  Future<void> _prepareSaveDir() async{
    _localPath = (await _findLocalPath())!;
    final savedDir = Directory(_localPath);
    bool hasExisted = await savedDir.exists();
    if (!hasExisted) {
      savedDir.create();
    }
  }

  Future<String?> _findLocalPath() async{
    String externalStorageDirPath;
    if(Platform.isAndroid){
      final directory = await getExternalStorageDirectory();
      externalStorageDirPath = directory!.path;
    }else{
      final directory = await getApplicationDocumentsDirectory();
      externalStorageDirPath = directory.path;
    }

    return externalStorageDirPath;
  }

  @override
  void dispose() {
    IsolateNameServer.removePortNameMapping('port');
    super.dispose();
  }

  static void downloadCallback(String id, DownloadTaskStatus status, int progress){
    print("Task $id: status: $status, progress: $progress");
    final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port')!;
    send.send([id, status, progress]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _isLoading ? null : AppBar(
        title: const Text('Catálogo general'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(
              Icons.share_outlined,
              color: Colors.white,
            ),
            padding: EdgeInsets.zero,
            onPressed: () => Share.share("https://www.solerpalau.mx/General/#page=1"),
          ),
          IconButton(
            icon: const Icon(
              Icons.file_download,
              color: Colors.white,
            ),
            padding: EdgeInsets.zero,
            onPressed: (){
              Fluttertoast.showToast(
                msg: "Descargando archivo...",
                toastLength: Toast.LENGTH_SHORT,
              );

              final task =  TaskInfo(name: "Catálogo General", link: "https://www.solerpalau.mx/ASW/recursos/cata/General.pdf");
              _requestDownload(task);
            },
          )
        ],
      ),
      body: _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : SafeArea(
        child: WebView(
          initialUrl: "https://www.solerpalau.mx/General/#page=1",
          javascriptMode: JavascriptMode.unrestricted,
          onWebViewCreated: (webViewController){
            _controller.complete(webViewController);
          },
        ),
      ),
    );
  }
}
