import 'dart:async';
import 'dart:typed_data';
import 'package:flutter/services.dart';

import 'main.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:unitstocks/unit_details.dart';
import 'Util/DBHelper.dart';
import 'Util/UnitModel.dart';
import 'Util/Util.dart';
import 'Util/photo_viewer.dart';
import 'package:barcode_scan/barcode_scan.dart';

class Stocking extends StatefulWidget {
  Stocking({Key key}) : super(key: key);

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

class _StockingState extends State<Stocking> with SingleTickerProviderStateMixin {
//  List<insertUnit> Units = [];
  List<Unit> unitsRef = [];
  List<blobImage> Blobs = [];
  List<blobImage> BlobsRef = [];
  bool completed = false;
  Util util = new Util();
  int totalUnit = 0;
  final search_controller = new TextEditingController();
//  TabController _tabBarcontroller;
  bool hideAppbar = false;
  String search = '';

  loadUnit()async{
    print('loading units');
    Blobs.clear();
    BlobsRef.clear();
    await DBHelper.database.closeDb();
//    Units = (search=='')?await DBHelper.database.getAllInsertUnits():await DBHelper.database.searchAllInsertUnits(search.toUpperCase());
    unitsRef = (search=='')?await DBHelper.database.getAllUnits(inserted: completed):await DBHelper.database.searchAllUnits(search.toUpperCase(),inserted: completed);
//    totalUnit = await DBHelper.database.getCount();
//    for (int i = 0;i<Units.length;i++){
//      var blob = await DBHelper.database.getBlobImage(Units[i].id);
//      Blobs.add(blob);
//    }
    for (int i = 0;i<unitsRef.length;i++){
      var blob = (unitsRef[i].mesin!=null)?await DBHelper.database.getBlobImage(unitsRef[i].mesin):null;
      BlobsRef.add(blob);
    }
    print([BlobsRef.length,unitsRef.length]);
    setState(() {
    });
  }

  Map<Function, Timer> _timeouts = {};
  void debounce(Duration timeout, Function target, [List arguments = const []]) {
    if (_timeouts.containsKey(target)) {
      _timeouts[target].cancel();
    }

    Timer timer = Timer(timeout, () {
      Function.apply(target, arguments);
    });

    _timeouts[target] = timer;
  }

  void _onChanged(String val)async {
    search = search_controller.text;
                await loadUnit();
  }

  Future scan() async {
    try {
      search = '';
      setState(() =>  search_controller.text = search);
      ScanResult result = await BarcodeScanner.scan();
      String barcode = result.rawContent;
      setState(() => this.search = barcode);
    } on PlatformException catch (e) {
      if (e.code == BarcodeScanner.cameraAccessDenied) {
        util.showFlushbar(context, 'The user did not grant the camera permission!',color: Colors.red);
        setState(() {
          this.search = '';
        });
      } else {
        util.showFlushbar(context, 'Unknown error: $e',color: Colors.red);
        setState(() => this.search = '');
      }
    } on FormatException {
      setState(() => this.search =
      '');
    } catch (e) {
      util.showFlushbar(context, 'Unknown error: $e',color: Colors.red);
      setState(() => this.search = '');
    }
    setState(() =>  search_controller.text = search);
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
//    _tabBarcontroller = new TabController(length: 1, vsync:this);
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      util.showLoading(context);
      await Future.sync(()async{await loadUnit();});
      Navigator.pop(context);
      if(locationStream==null)await util.streamLocation(context);
      else {
        if(locationStream.isPaused) locationStream.resume();
      }
//      setState(() {
//        unitsRef.add(new Unit(flag: 'False',tipe: "sdasdas",id: 2,mesin: "sdfasdas",kode: "dasdas",rangka: "asdasd",tahun: "2020",warna: "MERAH",state: "OnChanne;"));
//        unitsRef.add(new Unit(flag: 'False',tipe: "sdasdas",id: 2,mesin: "sdfasdas",kode: "dasdas",rangka: "asdasd",tahun: "2020",warna: "MERAH",state: "OnChanne;"));
//        unitsRef.add(new Unit(flag: 'False',tipe: "sdasdas",id: 2,mesin: "sdfasdas",kode: "dasdas",rangka: "asdasd",tahun: "2020",warna: "MERAH",state: "OnChanne;"));
//        unitsRef.add(new Unit(flag: 'False',tipe: "sdasdas",id: 2,mesin: "sdfasdas",kode: "dasdas",rangka: "asdasd",tahun: "2020",warna: "MERAH",state: "OnChanne;"));
//        unitsRef.add(new Unit(flag: 'False',tipe: "sdasdas",id: 2,mesin: "sdfasdas",kode: "dasdas",rangka: "asdasd",tahun: "2020",warna: "MERAH",state: "OnChanne;"));
//      });
    });
  }
  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    print('LocationStream paused');
    if(!locationStream.isPaused)locationStream.pause();
  }
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        if(hideAppbar) {
          setState(() {
            hideAppbar=false;
            search = '';
            search_controller.text = '';
          });
          await loadUnit();
          return false;
        }
        else {
          return true;
        }
      },
      child: Scaffold(
        appBar: (hideAppbar)?
        AppBar(
          backgroundColor: Colors.white,
          leading: GestureDetector(
              onTap:()async{
                setState(() {
                  hideAppbar=false;
                  search = '';
                  search_controller.text = '';
                });
                await loadUnit();
              },child: Container(width: 20,child: Icon(Icons.arrow_back,color:Colors.grey))),
          title: Container(
            color: Colors.white,
            child: TextFormField(
              maxLines: 1,
              controller: search_controller,
              onChanged: (val) => debounce(const Duration(milliseconds: 300), _onChanged, [val]),
//              onChanged: (value)async{
//                search = search_controller.text;
//                await loadUnit();
//              },
              decoration: InputDecoration.collapsed(
                hintText: 'Search..',
              ),
            ),
          ),
          actions: <Widget>[
            FlatButton(
              onPressed: ()async{await scan();await loadUnit();},
              child: Icon(Icons.select_all,color:Colors.grey),
            )
          ],
        )
            :null,
//        AppBar(
//          backgroundColor: Colors.indigo.withOpacity(0.8),
//          title: Text('Unit Stocking'),
//          actions: <Widget>[
//            IconButton(
//              icon: Icon(Icons.search,color:Colors.white),
//              onPressed: (){
//                setState(() {
//                  hideAppbar = true;
//                });
//              },
//            ),
//          ],
//        ),
        body: Column(
          children: <Widget>[
            (hideAppbar)?Container():SizedBox(height: MediaQuery.of(context).size.height/25,),
            Expanded(
                  child:Stack(
                    children: <Widget>[
                      Container(
                        child: ListView.builder(
                          padding: EdgeInsets.only(bottom: 10),
                          itemCount: unitsRef.length,
                          shrinkWrap: false,
                          itemBuilder: (context,index){
                            Uint8List display;
                            display = unitsRef[index].flag=='FALSE'?null:(BlobsRef.length==unitsRef.length)?BlobsRef[index].blob_file:null;
                            return Column(
                              children: <Widget>[
                                (index==0)?Container(padding: EdgeInsets.only(top: 10,left: 10,right: 10),alignment: Alignment.centerRight,
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: <Widget>[
                                      Row(
                                        children: <Widget>[
                                          Checkbox(
                                            value: completed,
                                            onChanged: (value)async{
                                              setState(() {
                                                completed = value;
                                              });
                                              await loadUnit();
                                            },
                                          ),
                                          Text('Completed')
                                        ],
                                      ),
                                      (completed||hideAppbar)?Container():Row(
                                        mainAxisAlignment: MainAxisAlignment.end,
                                        children: <Widget>[
                                          Text('Unit : ',style: TextStyle(color: Colors.grey,fontSize: 15),),
                                          Text('${(unitsRef.where((element) => element.flag=='TRUE').length==unitsRef.length)?'Done':'${unitsRef.length-unitsRef.where((element) => element.flag=='TRUE').length}'}',style: TextStyle(color: (unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?Colors.green:Colors.black,fontWeight: FontWeight.bold,fontSize: 16),),
                                          Text(!(unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?' of':'',style: TextStyle(color: Colors.grey,fontSize: 15),),
                                          Text(!(unitsRef.length==unitsRef.where((element) => element.flag=='TRUE').length)?' ${unitsRef.length}':'',style: TextStyle(color: Colors.black,fontSize: 16,fontWeight: FontWeight.bold,),),
                                        ],
                                      ),
                                    ],
                                  ),):Container(),
                                Padding(
                                  padding: const EdgeInsets.only(left:10,right: 10,top: 10),
                                  child: Container(
                                      padding: EdgeInsets.all(5.0),
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(5),
                                        color: Colors.white,
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.grey,
                                            blurRadius: 5.0, // has the effect of softening the shadow
                                            spreadRadius: 2.0, // has the effect of extending the shadow
                                            offset: Offset(
                                              00.0, // horizontal, move right 10
                                              2.0, // vertical, move down 10
                                            ),
                                          )
                                        ],
                                        border: Border.all(color: Colors.grey.withOpacity(0.5)),
                                      ),
                                      child:Row(
                                        children: <Widget>[
                                          Expanded(
                                              flex: 3,
                                              child: InkWell(
                                                onTap: ()async{
//                                              if(display!=null)Navigator.push(context, MaterialPageRoute(builder: (context) => PhotoViewer(Blobs[index].blob_file,id: Blobs[index].blob_id.toString(),edit: false,jenis: Blobs[index].jenis,)));
                                                    if(display==null){
                                                      var result = await Navigator.push(
                                                        context,
                                                        MaterialPageRoute(
                                                          builder: (context) => UnitDetails(unit: unitsRef[index],),
                                                        ),
                                                      );
                                                      if(result!=null){
                                                        util.showLoading(context);
                                                        await loadUnit();
                                                        Navigator.pop(context);
                                                      }
                                                    }
                                                    else{
                                                      await Navigator.push(context, MaterialPageRoute(builder: (context) => PhotoViewer(display,id: unitsRef[index].id.toString(),jenis: '',edit: false,)));
                                                    }
                                                  },
                                                child: Hero(tag: unitsRef[index].id,child: Padding(
                                                  padding: EdgeInsets.only(right: 10),
                                                  child: Container(width: 100,height: 100,alignment: Alignment.center,child:(display==null)?Icon(Icons.crop_original,color: Colors.white,size: 80,):null,
                                                      decoration: BoxDecoration(
                                                        color: Colors.grey.withOpacity(0.5),
                                                        image: (display!=null)?DecorationImage(
                                                            image: MemoryImage(display),fit: BoxFit.cover,):null,)),
                                                )),
                                              )),
                                          Expanded(
                                              flex: 7,
                                              child: InkWell(
                                                onTap: ()async{
                                                  var result;
//                                            if(display!=null) {
//                                              result = await Navigator.push(
//                                                context,
//                                                MaterialPageRoute(
//                                                  builder: (context) => UnitDetails(idInsert: unitsRef[index].mesin_id,),
//                                                ),
//                                              );
//                                            }
//                                                  if(display==null){
                                                    result = await Navigator.push(
                                                      context,
                                                      MaterialPageRoute(
                                                        builder: (context) => UnitDetails(unit: unitsRef[index],),
                                                      ),
                                                    );
//                                                  }
                                                  if(result!=null){
                                                    util.showLoading(context);
                                                    await loadUnit();
                                                    Navigator.pop(context);
                                                  }
                                                },
                                                child: SingleChildScrollView(
                                                  scrollDirection: Axis.horizontal,
                                                  child: Column(
                                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                                    crossAxisAlignment: CrossAxisAlignment.start,
                                                    children: <Widget>[
                                                      Text('Rangka : ${unitsRef[index].rangka}'),
                                                      Divider(height: 10,),
                                                      Text('Tipe : ${unitsRef[index].tipe}'),
                                                      Divider(height: 10,),
                                                      Row(
                                                        children: <Widget>[
//                                                    Container(width: MediaQuery.of(context).size.width*0.35,child: Text('State : ${unitsRef[index].state}')),
//                                                    Container(width: MediaQuery.of(context).size.width*0.5,child: Text('Tipe : ${unitsRef[index].tipe}',style: TextStyle(fontSize: 12),)),
                                                          Text('Timestamp : ${unitsRef[index].timestamp}'),
                                                        ],
                                                      ),
                                                      Divider(height: 10,),
                                                      Row(
                                                        children: <Widget>[
                                                          Container(width: MediaQuery.of(context).size.width*0.35,child: Text('Warna : ${unitsRef[index].warna}')),
                                                          Text('State : ${unitsRef[index].state}'),
                                                        ],
                                                      )
                                                    ],
                                                  ),
                                                ),
                                              )),
                                        ],
                                      )),
                                ),
                              ],
                            );
                          },
                        ),
                      ),
                    ],
                  ),
            ),
          ],
        ),
        floatingActionButton: FloatingActionButton(
          backgroundColor: Colors.indigo.withOpacity(0.8),
          onPressed: ()async{
            setState(() {
              hideAppbar = !(hideAppbar??false);
            });
//            var result = await Navigator.push(context, MaterialPageRoute(builder: (context)=>UnitDetails(unit: new Unit(flag: 'FALSE'),)));
//            if(result!=null){
//              util.showLoading(context);
//              await loadUnit();
//              Navigator.pop(context);
//            }
          },
          child: Icon(Icons.search,color:Colors.white),
        ),
      ),
    );
  }
}