import 'dart:async';
import 'dart:io';
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:path_provider/path_provider.dart';
import 'Util/DBHelper.dart';
import 'Util/Util.dart';
import 'Util/download_Upload_Handler.dart';
import 'package:intl/intl.dart';
import 'main.dart';
import 'Util/Prefs.dart';
import 'Util/UnitModel.dart';

class HomePage extends StatefulWidget {
//  HomePage({Key key}) : super(key: key);
  final String title;
  HomePage({this.title});
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Util util = new Util();
  StreamSubscription progressDLStream,progressULStream;
  String lastDownload = '';
  String lastUpload = '';
  double progressDL,progressUL;
  String timeString = '';
  bool isLoading = false;
  String state = '';
  final hostAddress = new TextEditingController();

  clearData(context)async{
    setState(() {
      progressDL = null;
      isLoading = false;
    });
    String errMsg;
    bool result = await showDialog(context: context,builder: (context)=>WillPopScope(
      onWillPop: ()async{
        Navigator.pop(context,false);
        return false;
      },
      child: AlertDialog(
        title: Text('Clear Data ?'),
        content: Text('Proceed to clear any remaining units data on this device?'),
        actions: <Widget>[
          FlatButton(
            child: Text('Proceed'),
            onPressed: ()async{
              util.showLoading(context);
              await Future.sync(()async{
                await prefs.remove(keyClass.lastDownload);
                await prefs.remove(keyClass.lastUpload);
                await prefs.remove(keyClass.targetProccess);
                await prefs.remove(keyClass.submitProccess);
                await prefs.remove(keyClass.stock_id);
                setState(() {
                  lastUpload = '';
                  lastDownload = '';
                  timeString = '';
                });
//                var result = await DBHelper.database.deleteAll();
//                if(result!=null) {
//                  await DBHelper.database.closeDb();
//                if(result!=null){
                    try{
                      Directory documentsDirectory = await getApplicationDocumentsDirectory();
                      String path = join(documentsDirectory.path, "UnitStocking.db");
                      File db = File(path);
                      if(db.existsSync()){
                        db.deleteSync();
                      }
                    }
                    catch(e){
                      print(e);
                      util.showFlushbar(context, 'Failed to delete database file',color: Colors.red);
                    }
//                }
//                else{
//                  errMsg = 'Failed to clear unit data';
//                }
//                }
//                else{
//                  errMsg = 'Failed to clear unit data';
//                }
              });
              Navigator.pop(context);
              Navigator.pop(context,true);
              util.showFlushbar(context,errMsg??'Data Cleared');
            },
          ),
          FlatButton(
            child: Text('Cancel'),
            onPressed: (){Navigator.pop(context,false);},
          )
        ],
      ),
    ));
    return result;
  }

  loadState()async{
    String company = prefs.getString(keyClass.company);
    String stock_taking_id = prefs.getString(keyClass.stock_id);

    if(company!=null&&stock_taking_id!=null){
      var result = await util.JsonDataPostRaw({"company":company,"stockTakingId":stock_taking_id}, '${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/getStateStockUnit');
      print(result);
      if(result['STATUS']==1){
        setState(() {
          state = result['DATA']['STATE'];
        });
      }
    }
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadState();
    lastDownload = prefs.getString(keyClass.lastDownload)??'';
    lastUpload = prefs.getString(keyClass.lastUpload)??'';
  }

  changeCabang(context)async{
    util.showLoading(context);
    var result = await util.JsonDataPostRaw({"company":prefs.getString(keyClass.company),"User":prefs.getString(keyClass.user_id)}, '${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/getCabangByUser');
    Navigator.pop(context);
    if(result['STATUS']==1){
      var selected = prefs.getString(keyClass.cabang_id)??result['DATA'][0]["RETURN_VALUE"];
      return await showDialog(context: context,builder: (context)=>StatefulBuilder(
        builder:(context,setState)=>
            Material(
              color: Colors.white.withOpacity(0.9),
              child: Center(
                child: Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                      borderRadius: BorderRadius.circular(5)
                  ),
                  height: MediaQuery.of(context).size.height/3.2,
                  width: MediaQuery.of(context).size.width*0.75,
                  child: Column(
                    children: <Widget>[
                      Flexible(
                        flex:3,
                        child: Container(
                          padding: EdgeInsets.only(top:10,left: 10,right: 10),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
//                          color: Colors.indigo,
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                          ),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Icon(Icons.business,size: 70,color: Colors.indigo,),
                              SizedBox(height: 5,),
                              Text('Set Cabang',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16,color: Colors.indigo),)
                            ],
                          ),
                        ),
                      ),
                      Flexible(
                        flex: 1,
                        child: Container(
                          padding: EdgeInsets.only(left: 20,right: 20),
                          alignment: Alignment.centerLeft,
                          child: Theme(
                            data: ThemeData(
                                canvasColor: Colors.white,
                                primaryColor: Colors.indigo,
                                accentColor: Colors.indigo,
                                hintColor: Colors.indigo
                            ),
                            child: DropdownButtonFormField(
                              style: TextStyle(color: Colors.black.withOpacity(0.6),fontWeight: FontWeight.w500,fontSize: 14,),
                              decoration: InputDecoration(
                                contentPadding: EdgeInsets.all(8.0),
                              ),
                              value: selected,
                              onChanged: (value){
                                setState(() {
                                  selected = value;
                                });
                              },
                              items: result['DATA'].map<DropdownMenuItem<dynamic>>((item){
                                return DropdownMenuItem(
                                  value: item['RETURN_VALUE'],
                                  child: Text(item["DISPLAY_VALUE"]),
                                );
                              }).toList(),
                            ),
                          ),
                        ),
                      ),
                      Flexible(
                        flex: 1,
                        child: Container(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              FlatButton(
                                child: Text('OK',style: TextStyle(color: Colors.indigo),),
                                onPressed: ()async{
                                  if(selected!=prefs.getString(keyClass.cabang_id)){
                                    prefs.setString(keyClass.cabang_id,selected);
                                    await Future.sync(()async{
                                      await prefs.remove(keyClass.lastDownload);
                                      await prefs.remove(keyClass.lastUpload);
                                      await prefs.remove(keyClass.targetProccess);
                                      await prefs.remove(keyClass.submitProccess);
                                      lastUpload = '';
                                      lastDownload = '';
                                      timeString = '';
                                      try{
                                        Directory documentsDirectory = await getApplicationDocumentsDirectory();
                                        String path = join(documentsDirectory.path, "UnitStocking.db");
                                        File db = File(path);
                                        if(db.existsSync()){
                                          db.deleteSync();
                                        }
                                      }
                                      catch(e){
                                        print(e);
                                        util.showFlushbar(context, 'Failed to delete database file',color: Colors.red);
                                      }
                                    });
                                    Navigator.pop(context,true);
                                  }
                                  else{
                                    Navigator.pop(context,false);
                                  }
                                },
                              ),
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
//            AlertDialog(
//          title: Text('Set Cabang'),
//          content: DropdownButtonFormField(
//            value: selected,
//            onChanged: (value){
//              setState(() {
//                selected = value;
//              });
//            },
//            items: result['DATA'].map<DropdownMenuItem<dynamic>>((item){
//              return DropdownMenuItem(
//                value: item['RETURN_VALUE'],
//                child: Text(item["DISPLAY_VALUE"]),
//              );
//            }).toList(),
//          ),
//          actions: <Widget>[
//            FlatButton(
//              child: Text('OK'),
//              onPressed: ()async{
//                if(selected!=prefs.getString(keyClass.cabang_id)){
//                  prefs.setString(keyClass.cabang_id,selected);
//                  await Future.sync(()async{
//                    await prefs.remove(keyClass.lastDownload);
//                    await prefs.remove(keyClass.lastUpload);
//                    await prefs.remove(keyClass.targetProccess);
//                    await prefs.remove(keyClass.submitProccess);
//                    lastUpload = '';
//                    lastDownload = '';
//                    timeString = '';
////                var result = await DBHelper.database.deleteAll();
////                if(result!=null) {
////                  await DBHelper.database.closeDb();
////                if(result!=null){
//                    try{
//                      Directory documentsDirectory = await getApplicationDocumentsDirectory();
//                      String path = join(documentsDirectory.path, "UnitStocking.db");
//                      File db = File(path);
//                      if(db.existsSync()){
//                        db.deleteSync();
//                      }
//                    }
//                    catch(e){
//                      print(e);
//                      util.showFlushbar(context, 'Failed to delete database file',color: Colors.red);
//                    }
////                }
////                else{
////                  errMsg = 'Failed to clear unit data';
////                }
////                }
////                else{
////                  errMsg = 'Failed to clear unit data';
////                }
//                  });
//                  Navigator.pop(context,true);
//                }
//                else{
//                  Navigator.pop(context,false);
//                }
////                util.showLoading(context);
//
////                Navigator.pop(context);
//              },
//            )
//          ],
//        ),
      ));
    }
    else{
      util.showFlushbar(context, result['DATA'],color: Colors.red);
      return false;
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: ()async{
        await showDialog(context: context,builder: (context)=>
            Material(
              color: Colors.white.withOpacity(0.9),
              child: Center(
                child: Container(
                  decoration: BoxDecoration(
                      color: Colors.white,
                      boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                      borderRadius: BorderRadius.circular(5)
                  ),
                  height: MediaQuery.of(context).size.height/4.8,
                  width: MediaQuery.of(context).size.width*0.75,
                  child: Column(
                    children: <Widget>[
                      Flexible(
                        flex:3,
                        child: Container(
                          padding: EdgeInsets.only(top:10,left: 10,right: 10),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
//                          color: Colors.indigo,
                              borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                          ),
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: <Widget>[
                              Icon(Icons.exit_to_app,size: 70,color: Colors.indigo,),
                            ],
                          ),
                        ),
                      ),
                      Flexible(
                        flex: 1,
                        child: Container(
                          padding: EdgeInsets.only(left: 20,right: 20),
                          alignment: Alignment.centerLeft,
                            child: Text('Keluar dari aplikasi?',style: TextStyle(fontWeight: FontWeight.w500,fontSize: 14,color: Colors.black.withOpacity(0.6)),)
                        ),
                      ),
                      Flexible(
                        flex: 1,
                        child: Container(
                          padding: EdgeInsets.only(bottom:10),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: <Widget>[
                              FlatButton(
                                child: Text('Exit',style: TextStyle(color: Colors.indigo),),
                                onPressed: ()async{
                                  Navigator.pop(context);
                                  await locationStream?.cancel();
                                  exit(0);
                                },
                              ),
                              FlatButton(
                                child: Text('Cancel',style: TextStyle(color: Colors.indigo),),
                                onPressed: (){
                                  Navigator.pop(context);
                                },
                              )
                            ],
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ),
            ),
        );
        return false;
      },
      child: Scaffold(
          body: Column(
            crossAxisAlignment: CrossAxisAlignment.end,
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(bottom: 0,left: 15,right: 10,top: 10),
                height: MediaQuery.of(context).size.height/13,
                width: MediaQuery.of(context).size.width,
                alignment: Alignment.bottomLeft,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    Text('Home',style: TextStyle(color: Colors.indigo.withOpacity(0.8),fontSize: 18,fontWeight: FontWeight.bold),),
                    PopupMenuButton(
                      child: Padding(
                        padding: const EdgeInsets.only(right:2.0),
                        child: Icon(Icons.menu,color: Colors.indigo.withOpacity(0.8),),
                      ),
                      itemBuilder: (context){
                        return [
                          PopupMenuItem(
                            value:'hostChange',
                            child: Row(
                              children: <Widget>[
                                Icon(Icons.network_wifi,color: Colors.black,),
                                SizedBox(width: 10,),
                                Text('Change Ip Address')
                              ],
                            ),
                          ),
                          PopupMenuItem(
                            value:'cabangChange',
                            child: Row(
                              children: <Widget>[
                                Icon(Icons.business,color: Colors.black,),
                                SizedBox(width: 10,),
                                Text('Change Cabang')
                              ],
                            ),
                          ),
                          PopupMenuItem(
                            value:'logout',
                            child: Row(
                              children: <Widget>[
                                Icon(Icons.exit_to_app,color: Colors.black,),
                                SizedBox(width: 10,),
                                Text('Logout')
                              ],
                            ),
                          ),
                        ];
                      },
                      onSelected: (value)async{
                        if(value == 'hostChange'){
                          hostAddress.text = prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id';
                          await showDialog(context: context,builder: (context)=>
                              Material(
                                color: Colors.white.withOpacity(0.9),
                                child: Center(
                                  child: Container(
                                    decoration: BoxDecoration(
                                        color: Colors.white,
                                        boxShadow: [
                                          BoxShadow(
                                            color: Colors.grey.withOpacity(0.5),
                                            spreadRadius: 2,
                                            blurRadius: 2,
                                            offset: Offset(0, 0), // changes position of shadow
                                          ),
                                        ],
                                        borderRadius: BorderRadius.circular(5)
                                    ),
                                    height: MediaQuery.of(context).size.height/3.2,
                                    width: MediaQuery.of(context).size.width*0.75,
                                    child: Column(
                                      children: <Widget>[
                                        Flexible(
                                          flex:3,
                                          child: Container(
                                            padding: EdgeInsets.only(top:10,left: 10,right: 10),
                                            alignment: Alignment.center,
                                            decoration: BoxDecoration(
//                          color: Colors.indigo,
                                                borderRadius: BorderRadius.only(topLeft: Radius.circular(5),topRight: Radius.circular(5))
                                            ),
                                            child: Column(
                                              mainAxisSize: MainAxisSize.min,
                                              crossAxisAlignment: CrossAxisAlignment.center,
                                              children: <Widget>[
                                                Icon(Icons.network_wifi,size: 70,color: Colors.indigo,),
                                                SizedBox(height: 5,),
                                                Text('Set Ip Address',style: TextStyle(fontWeight: FontWeight.bold,fontSize: 16,color: Colors.indigo),)
                                              ],
                                            ),
                                          ),
                                        ),
                                        Flexible(
                                          flex: 1,
                                          child: Container(
                                            padding: EdgeInsets.only(left: 20,right: 20),
                                            alignment: Alignment.centerLeft,
                                            child: Theme(
                                              data: ThemeData(
                                                  canvasColor: Colors.white,
                                                  primaryColor: Colors.indigo,
                                                  accentColor: Colors.indigo,
                                                  hintColor: Colors.indigo
                                              ),
                                              child: TextField(
                                                controller: hostAddress,
                                                decoration: InputDecoration(
                                                  contentPadding: EdgeInsets.all(8),
                                                ),
                                                onSubmitted: (value){
                                                  prefs.setString(keyClass.hostAddress,(value=='')?'https://unitstocksbackend.thamringroup.web.id':value);
                                                  Navigator.pop(context);
                                                },
                                              ),
                                            ),
                                          ),
                                        ),
                                        Flexible(
                                          flex: 1,
                                          child: Container(
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.end,
                                              children: <Widget>[
                                                FlatButton(
                                                  child: Text('OK',style: TextStyle(color: Colors.indigo),),
                                                  onPressed: (){
                                                    prefs.setString(keyClass.hostAddress,(hostAddress.text=='')?'https://unitstocksbackend.thamringroup.web.id':hostAddress.text);
                                                    Navigator.pop(context);
                                                  },
                                                )
                                              ],
                                            ),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              )
//                      AlertDialog(
//                    title: Text('Set IP Address'),
//                    content: TextField(
//                      controller: hostAddress,
//                      onSubmitted: (value){
//                        prefs.setString(keyClass.hostAddress,(value=='')?'https://unitstocksbackend.thamringroup.web.id':value);
//                        Navigator.pop(context);
//                      },
//                    ),
//                    actions: <Widget>[
//                      FlatButton(
//                        child: Text('OK'),
//                        onPressed: (){
//                          prefs.setString(keyClass.hostAddress,(hostAddress.text=='')?'https://unitstocksbackend.thamringroup.web.id':hostAddress.text);
//                          Navigator.pop(context);
//                        },
//                      )
//                    ],
//                  )
                          );
                        }
                        if(value=="cabangChange") {
                          var res = await changeCabang(context);
                          if(res??false){
                            setState(() {
                            });
                          }
                        }
                        if(value == 'logout'){
                          prefs.remove(keyClass.cabang_id);
                          prefs.remove(keyClass.company);
                          prefs.remove(keyClass.user_id);
                          prefs.setBool(keyClass.logged_in, false);
                          Navigator.pushNamed(context, '/login');
                        }
                      },
                    ),
                  ],
                ),
              ),
              (prefs.getString(keyClass.stock_id)==null)?Container():Padding(
                padding: const EdgeInsets.only(top: 8,right: 8),
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.indigo.withOpacity(0.9),
                    borderRadius: BorderRadius.circular(8)
//                    border: Border.all(),
                  ),
                  padding: EdgeInsets.all(8),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    mainAxisAlignment: MainAxisAlignment.end,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      Text('Status : ',style: TextStyle(color: Colors.white),),
                      Text(state??'-',style: TextStyle(fontWeight: FontWeight.bold,color: Colors.white),),
                    ],
                  ),
                ),
              ),
              Expanded(
                child: Container(
                child:
                GridView.count(
                  padding: EdgeInsets.all(10),
                  crossAxisSpacing: 10,
                  mainAxisSpacing: 10,
                  crossAxisCount: 2,
                  children: <Widget>[
                    AbsorbPointer(
                      absorbing: isLoading,
                      child: InkWell(
                        splashColor: Colors.black,
                        onTap: ()async{
                          bool getData = await showDialog(
                            context: context,
                            builder: (context)=>AlertDialog(
                              title: Text("Get Data Units?"),
                              content: Text('Fetch data unit for stocking'),
                              actions: <Widget>[
                                FlatButton(
                                  child: Text('Proceed'),
                                  onPressed: (){
                                    Navigator.pop(context,true);
                                  },
                                ),
                                FlatButton(
                                  child: Text('Cancel'),
                                  onPressed: (){
                                    Navigator.pop(context,false);
                                  },
                                )
                              ],
                            )
                          );
                          if(getData??false){
                            setState(() {
                              isLoading = true;
                            });
                            var a = Stopwatch();
                            a.start();
                            await Future.delayed(Duration(milliseconds: 200));
                            bool isclear;
                            Directory documentsDirectory = await getApplicationDocumentsDirectory();
                            String path = join(documentsDirectory.path, "UnitStocking.db");
                            File db = File(path);
                            if(db.existsSync()){
                              isclear = await clearData(context);
                            }
                            else{
                              isclear = true;
                            }
                            if(isclear??false){
                              print('fetching');
                              util.showLoading(context);
                              file_Trans_Handler trans = new file_Trans_Handler();
                              trans.downloadFile('UnitStocking.db',"${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/getSqliteDb/${prefs.getString(keyClass.company)}/${prefs.getString(keyClass.cabang_id)}");
                              progressDLStream = trans.progress.listen((value)async {
                                if(progressDL==null) {
//                                print(['test',value]);
                                  if(value!=null) Navigator.pop(context);
                                }
                                setState(() {
                                  progressDL = (value!=-1.0)?value:null;
                                });
                                if(value!=null&&value >= 1.0) {
                                  progressDLStream.cancel();
                                  progressDL = null;
                                  setState(() {
                                    lastDownload = DateTime.now().toIso8601String();
                                  });
                                  await prefs.setString(keyClass.lastDownload, lastDownload);
                                  await DBHelper.database.insertUpdateValue(new valueTab(name: 'TGL_START',value: DateFormat('dd-MM-yyyy HH:mm:ss').format(DateTime.parse(lastDownload))));
                                  await DBHelper.database.insertUpdateValue(new valueTab(name: 'TGL_STOCK_TAKING',value: DateFormat('dd-MM-yyyy').format(DateTime.parse(lastDownload))));
                                  await DBHelper.database.closeDb();
                                  util.showFlushbar(context,'Data downloaded');
                                  loadState();
                                  a.stop();
                                  if(a.elapsed.inSeconds<3){
                                    await Future.delayed(Duration(seconds: 3-a.elapsed.inSeconds));
                                  }
                                  setState(() {
                                    isLoading = false;
                                  });
                                }
                                if(value==-1.0){
                                  setState(() {
                                    isLoading = false;
                                  });
                                  util.showFlushbar(context,'Data download error',color: Colors.red);
                                }
                              });
//                            Navigator.popUntil(context, ModalRoute.withName('/home'));
                            }
                          }
                        },
                        child: Container(
                          padding: EdgeInsets.all(5),
                          decoration: BoxDecoration(
                            boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                            borderRadius: BorderRadius.all(Radius.circular(5.0)),
                            color: Colors.green.withAlpha(220).withOpacity(0.7),
                          ),
                          child: Stack(
                            children: <Widget>[
                              Container(
                                alignment: (progressDL!=null)?Alignment.bottomCenter:Alignment.bottomLeft,
                                padding: EdgeInsets.only(left: 10,right: 10,top: 10,bottom: 15),
                                child: (progressDL!=null)?Column(
                                  mainAxisSize: MainAxisSize.min,
                                  children: <Widget>[
                                    LinearProgressIndicator(
                                      value: progressDL,
                                    ),
                                    Text('${(progressDL*100).floor()}%',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),)
                                  ],
                                ):(lastDownload=='')?null:Text('Last download : ${DateFormat('dd MMM yyyy HH:mm').format(DateTime.parse(lastDownload))}',style: TextStyle(color: Colors.white,fontSize: 11,fontWeight: FontWeight.bold)),
                              ),
                              Positioned.fill(
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Icon(Icons.file_upload,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                                    SizedBox(height: 5,),
                                    Text('Get Data Master',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                    InkWell(
                      splashColor: Colors.black,
                      onTap: ()async{
                        await Future.delayed(Duration(milliseconds: 200));
                        if(lastDownload!=''){
                          Navigator.pushNamed(context, '/stocking');
                        }
                        else{
                          util.showFlushbar(context, 'Data Master tidak ditemukan. Get data master dulu.');
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          color: Colors.blueGrey.withAlpha(230).withOpacity(0.8),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.receipt,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                            SizedBox(height: 5,),
                            Text('Stocking',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),)
                          ],
                        ),
                      ),
                    ),
                    InkWell(
                      splashColor: Colors.black,
                      onTap: ()async{
                        if(lastDownload!=''){
                          await DBHelper.database.insertUpdateValue(new valueTab(name: 'TGL_SELESAI',value: DateFormat('dd-MM-yyyy HH:mm:ss').format(new DateTime.now())));
                          await DBHelper.database.closeDb();
                          file_Trans_Handler trans = new file_Trans_Handler();
                          bool popped = false;
                          util.showLoading(context,onwillpop:()async{
                            await trans.cancel();
                            popped = true;
                            return true;
                          });
                          var upload = await trans.uploadFile('UnitStocking.db',"${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/uploadSqlitedb",prefs.getString(keyClass.company),prefs.getString(keyClass.cabang_id));
                          if(!popped){
                            Navigator.pop(context);
                            util.showFlushbar(context, upload['DATA'],color:(upload['STATUS']!=1)?Colors.red:Colors.grey);
                            if(upload['STATUS']==1){
                              setState(() {
                                lastUpload = new DateTime.now().toIso8601String();
                              });
                              prefs.setString(keyClass.lastUpload, lastUpload);
                              prefs.setString(keyClass.targetProccess, upload[keyClass.targetProccess]);
                            }
                          }
                        }
                        else{
                          util.showFlushbar(context, "Belum ada data yang disimpan.",color: Colors.red);
                        }
                        },
                      child: Container(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          color: Colors.indigo.withAlpha(220).withOpacity(0.7),
                        ),
                        child: Stack(
                          children: <Widget>[
                            Container(
                              alignment: (progressUL!=null)?Alignment.bottomCenter:Alignment.bottomLeft,
                              padding: EdgeInsets.only(left: 10,right: 10,top: 10,bottom: 15),
                              child: (progressUL!=null)?Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  LinearProgressIndicator(
                                    value: progressUL,
                                  ),
                                  Text('${(progressUL*100).floor()}%',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold),)
                                ],
                              ):(lastUpload=='')?null:Text('Last upload : ${DateFormat('dd MMM yyyy HH:mm').format(DateTime.parse(lastUpload))}\n${(timeString!='')?'Duration: $timeString':''}',style: TextStyle(color: Colors.white,fontSize: 11,fontWeight: FontWeight.bold)),
                            ),
                            Positioned.fill(
                              child: Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Icon(Icons.file_upload,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                                  SizedBox(height: 5,),
                                  Text('Send Data Stokan',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),),
                                ],
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                    (prefs.getString(keyClass.targetProccess)==null&&prefs.getBool(keyClass.submitProccess)==null)?InkWell(
                      splashColor: Colors.black,
                      onTap: ()async{
                        await Future.delayed(Duration(milliseconds: 200));
                        await clearData(context);
                      },
                      child: Container(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          color: Colors.red.withAlpha(200).withOpacity(0.7),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.restore_from_trash,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                            SizedBox(height: 5,),
                            Text('Clear Data',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),)
                          ],
                        ),
                      ),
                    ):
                    (prefs.getString(keyClass.targetProccess)!=null)?InkWell(
                      onTap: ()async{
                        bool result = await showDialog(context: context,builder: (context)=>WillPopScope(
                          onWillPop: ()async{
                            Navigator.pop(context,false);
                            return false;
                          },
                          child: AlertDialog(
                            title: Text('Process Data ?'),
                            content: Text('Proceed to unpack the uploaded data.'),
                            actions: <Widget>[
                              FlatButton(
                                child: Text('Proceed'),
                                onPressed: ()async{
                                  Navigator.pop(context,true);
                                },
                              ),
                              FlatButton(
                                child: Text('Cancel'),
                                onPressed: (){Navigator.pop(context,false);},
                              )
                            ],
                          ),
                        ));
                        if(result){
                          util.showLoading(context);
                          file_Trans_Handler trans = new file_Trans_Handler();
                          var upload = await trans.unPackDb("${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/unpackDb",prefs.getString(keyClass.company),prefs.getString(keyClass.cabang_id),prefs.getString(keyClass.targetProccess));
                          Navigator.pop(context);
                          util.showFlushbar(context, upload['DATA'],color:(upload['STATUS']!=1)?Colors.red:Colors.grey);
                          if(upload['STATUS']==1){
                            prefs.remove(keyClass.targetProccess);
                            prefs.setBool(keyClass.submitProccess,true);
                          }
                          setState(() {

                          });
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          color: Colors.orangeAccent.withAlpha(230).withOpacity(0.7),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.arrow_forward,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                            SizedBox(height: 5,),
                            Text('Process Units',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),)
                          ],
                        ),
                      ),
                    ):
                    InkWell(
                      onTap: ()async{
                        bool result = await showDialog(context: context,builder: (context)=>WillPopScope(
                          onWillPop: ()async{
                            Navigator.pop(context,false);
                            return false;
                          },
                          child: AlertDialog(
                            title: Text('Submit Data ?'),
                            content: Text('Submit the uploaded data.'),
                            actions: <Widget>[
                              FlatButton(
                                child: Text('Submit'),
                                onPressed: ()async{
                                  Navigator.pop(context,true);
                                },
                              ),
                              FlatButton(
                                child: Text('Cancel'),
                                onPressed: (){Navigator.pop(context,false);},
                              )
                            ],
                          ),
                        ));
                        if(result){
                          util.showLoading(context);
                          file_Trans_Handler trans = new file_Trans_Handler();
                          var upload = await trans.submitDb("${prefs.getString(keyClass.hostAddress)??'https://unitstocksbackend.thamringroup.web.id'}/submitStock",prefs.getString(keyClass.company),prefs.getString(keyClass.stock_id));
                          Navigator.pop(context);
                          util.showFlushbar(context, upload['DATA'],color:(upload['STATUS']!=1)?Colors.red:Colors.grey);
                          if(upload['STATUS']==1){
                            loadState();
                            prefs.remove(keyClass.submitProccess);
                          }
                          setState(() {
                          });
                        }
                      },
                      child: Container(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          color: Colors.lightGreen.withAlpha(230),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.arrow_forward,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                            SizedBox(height: 5,),
                            Text('Submit Process',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),)
                          ],
                        ),
                      ),
                    ),
                    (prefs.getString(keyClass.targetProccess)!=null||(prefs.getBool(keyClass.submitProccess)!=null&&prefs.getBool(keyClass.submitProccess)))?InkWell(
                      splashColor: Colors.black,
                      onTap: ()async{
                        await Future.delayed(Duration(milliseconds: 200));
                        await clearData(context);
                      },
                      child: Container(
                        padding: EdgeInsets.all(5),
                        decoration: BoxDecoration(
                          boxShadow: [
                              BoxShadow(
                                color: Colors.grey.withOpacity(0.5),
                                spreadRadius: 2,
                                blurRadius: 2,
                                offset: Offset(0, 0), // changes position of shadow
                              ),
                            ],
                          borderRadius: BorderRadius.all(Radius.circular(5.0)),
                          color: Colors.red.withAlpha(200),
                        ),
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: <Widget>[
                            Icon(Icons.restore_from_trash,size: MediaQuery.of(context).size.width/6,color: Colors.white,),
                            SizedBox(height: 5,),
                            Text('Clear Data',style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 16),)
                          ],
                        ),
                      ),
                    ):Container(),
                  ],
                )),
              ),
            ],
          ),
        bottomSheet: Container(height: 22,alignment: Alignment.bottomRight,child: Opacity(opacity: 0.5,child: Padding(padding: EdgeInsets.all(5),child: Text((lastDownload!='')?'Master Data Downloaded':'No Master Data Found',style: TextStyle(fontSize: 12),)))),
      ),
    );

  }
}