import 'dart:io';

import 'package:flutter/material.dart';
import 'package:easy_pdf_viewer/easy_pdf_viewer.dart' as view;
import 'package:share_plus/share_plus.dart';

class PDFViewer extends StatefulWidget {
  final bool localFile;
  final File? file;
  final String? url;

  const PDFViewer({
    Key? key,
    required this.localFile,
    this.file,
    this.url
  }) : super(key: key);

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

class _PDFViewerState extends State<PDFViewer> {
  //late PdfViewerController _pdfViewerController;
  late view.PDFDocument doc;
  bool _multiplePages = false;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    loadFile();
    //_pdfViewerController = PdfViewerController();
  }
  
  void loadFile() async{
    if(widget.localFile){
      doc = await view.PDFDocument.fromFile(widget.file!);
    }else{
      doc = await view.PDFDocument.fromURL(widget.url!);
    }

    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    final path = widget.localFile ? widget.file!.path.split('/') : widget.url!.split('/');
    return Scaffold(
      appBar: AppBar(
        centerTitle: false,
        title: Text(
            widget.localFile ? path.last : path.last.replaceAll("%20", ""),
            textAlign: TextAlign.center,
            style: const TextStyle(
                color: Colors.white,
                fontFamily: 'Helvetica Neue Black Cond'
            )
        ),
        actions: <Widget>[
          IconButton(
            icon: const Icon(
              Icons.share,
              color: Colors.white,
            ),
            onPressed: (){
              shareFile();
            },
          ),
          if(_multiplePages)
            IconButton(
              icon: const Icon(
                Icons.keyboard_arrow_up,
                color: Colors.white,
              ),
              onPressed: () {
                //_pdfViewerController.previousPage();
              },
            ),
          if(_multiplePages)
            IconButton(
              icon: const Icon(
                Icons.keyboard_arrow_down,
                color: Colors.white,
              ),
              onPressed: () {
                //_pdfViewerController.nextPage();
              },
            )
        ],
      ),
      body: _isLoading ? const Center(
        child: CircularProgressIndicator(),
      ) : view.PDFViewer(
        document: doc,
        showNavigation: true,
      ),
    );
  }

  Future<void> shareFile() async {
    final path = widget.localFile ? widget.file!.path.split('/') : widget.url!.split('/');
    if(widget.localFile){
      Share.shareFiles([widget.file!.path], text: path.last);
    }else{
      Share.share(widget.url!, subject: path.last.replaceAll("%20", ""));
    }
  }
}
