import 'dart:async';
import 'dart:io';

import 'package:fcs/helpers/cache_mgr.dart';
import 'package:fcs/helpers/theme.dart';
import 'package:fcs/pages/main/util.dart';
import 'package:fcs/pages/widgets/progress.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:share/share.dart';

class PDFScreen extends StatefulWidget {
  final String title;
  final String url;

  PDFScreen({Key key, this.url, this.title}) : super(key: key);

  _PDFScreenState createState() => _PDFScreenState();
}

class _PDFScreenState extends State<PDFScreen> with WidgetsBindingObserver {
  final Completer<PDFViewController> _controller =
      Completer<PDFViewController>();
  int pages = 0;
  int currentPage = 0;
  bool isReady = false;
  String errorMessage = '';
  bool _isLoading = true;

  void initState() {
    super.initState();
    download();
  }

  File file;
  Future<void> download() async {
    try {
      File f = await PdfCacheMgr.pdfs.getSingleFile(widget.url);
      setState(() {
        file = f;
      });
    } catch (e) {
      showMsgDialog(context, "Error", e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return LocalProgress(
      inAsyncCall: _isLoading,
      child: Scaffold(
        appBar: AppBar(
          centerTitle: true,
          backgroundColor: Colors.white,
          shadowColor: Colors.transparent,
          title:
              Text(widget.title ?? "", style: TextStyle(color: primaryColor)),
          leading: new IconButton(
            icon: new Icon(CupertinoIcons.back, color: primaryColor),
            onPressed: () => Navigator.of(context).pop(),
          ),
          actions: <Widget>[
            IconButton(
              icon: Icon(
                Icons.share,
                color: primaryColor,
              ),
              onPressed: _share,
            ),
          ],
        ),
        body: Stack(
          children: <Widget>[
            _isLoading
                ? Container()
                : PDFView(
                    filePath: file?.path ?? "",
                    enableSwipe: true,
                    swipeHorizontal: true,
                    autoSpacing: false,
                    pageFling: true,
                    pageSnap: true,
                    defaultPage: currentPage,
                    fitPolicy: FitPolicy.BOTH,
                    preventLinkNavigation:
                        false, // if set to true the link is handled in flutter
                    onRender: (_pages) {
                      print(('pages => $pages'));
                      setState(() {
                        pages = _pages;
                        isReady = true;
                      });
                    },
                    onViewCreated: (PDFViewController pdfViewController) {
                      _controller.complete(pdfViewController);
                    },
                    onLinkHandler: (String uri) {
                      print('goto uri: $uri');
                    },
                    onPageChanged: (int page, int total) {
                      print('page change: $page/$total');
                      setState(() {
                        currentPage = page;
                      });
                    },
                  ),
          ],
        ),
      ),
    );
  }

  _share() async {
    final RenderBox box = context.findRenderObject();
    await Share.shareFiles([file.path],
        mimeTypes: ["application/pdf"],
        subject: "File",
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
  }
}
