import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:path_provider/path_provider.dart';
import 'package:http/http.dart';
class file_Trans_Handler {

//  double _progress = 0;
  String _path = '';
  StreamSubscription dlulStream;
  String _error = '';
  get path => _path;
  get error => _error;
  StreamController _progress = new StreamController<double>();
  Stream<double> get progress =>_progress.stream;
  var client = new Client();

  downloadFile(String fileName,String link) async {
    StreamedResponse _response;
    List<int> _bytes = [];
    int _total = 0;
    print('Start Download');
    _progress.add(null);
    try {
      Request req = new Request('GET', Uri.parse(link));
//      req.headers = '';
      _response = await client.send(req).timeout(
          Duration(seconds: 20));
//      _response = await client.get('$link',headers: 'application/json')
      _total = _response.contentLength;
      print('${_total / 1024} KB');
      dlulStream = _response.stream.listen((value) {
        _bytes.addAll(value);
        _progress.add(((_bytes.length / _total)));
      })
        ..onDone(() async {
          _progress.add(0.0);
          print('Finish Download');
          final file = File(
              "${(await getApplicationDocumentsDirectory()).path}/$fileName");
          await file.writeAsBytes(_bytes);
          _path = file.path;
        })
        ..onError((e) async {
          print('Error Download, $e');
          _progress.add(-1.0);
          _error = e.toString();
        });
    }
    catch(e){
      print('Error Download, $e');
      _progress.add(-1.0);
      _error = e.toString();
    }
  }

  uploadFile(String fileName,String link,String company,String cabang_id) async{
    final file = File(
        "${(await getApplicationDocumentsDirectory()).path}/$fileName");
    if(file.existsSync()){
      Uint8List byte = file.readAsBytesSync();
//      print("file size ${file.lengthSync()/1024}");
      try{
        var _reponse = await client.post(
            '$link', headers: {'Content-type': 'application/json'},
            body: json.encode({"byte":byte,"cabangId":cabang_id,"company":company}));
        print('File send ${file.lengthSync()/1024} KB');
        final Map data = JsonDecoder().convert(_reponse.body);
//        print(_reponse.body);
//        if(data['STATUS']==1){
//          return {"STATUS":1,"DATA":'File send ${file.lengthSync()/1024} KB'};
//        }
//        else {
          return data;
//        }
      }
      catch(e){
        print(e);
        return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
      }
    }
    else{
      return {"STATUS":0,"DATA":'No such file'};
    }
  }

  unPackDb(String link,String company,String cabang_id,String dbPath) async{
      try{
        var _reponse = await client.post(
            '$link', headers: {'Content-type': 'application/json'},
            body: json.encode({"cabangId":cabang_id,"company":company,"dbPath":dbPath}));
        final Map data = JsonDecoder().convert(_reponse.body);
        return data;
      }
      catch(e){
        print(e);
        return {"STATUS":0,"DATA":'Upload timeout. Make sure server is up and running'};
      }
  }

  submitDb(String link,String company,String stock_id) async{
    try{
      var _reponse = await client.post(
          '$link', headers: {'Content-type': 'application/json'},
          body: json.encode({"stockTakingId":stock_id,"company":company}));
      final Map data = JsonDecoder().convert(_reponse.body);
      return data;
    }
    catch(e){
      print(e);
      return {"STATUS":0,"DATA":'Request timeout. Make sure server is up and running'};
    }
  }

  uploadMultipart(String fileName,String link)async{
    StreamedResponse _response;
    List<int> _bytes = [];
    int _total = 0;
    var request = MultipartRequest('POST', Uri.parse(link));
    request.files.add(
        await MultipartFile.fromPath(
            'picture',
            "${(await getApplicationDocumentsDirectory()).path}/$fileName"
        )
    );
    _response = await client.send(request);
    _total = File("${(await getApplicationDocumentsDirectory()).path}/$fileName").lengthSync();
    dlulStream = _response.stream.listen((value) {
      _bytes.addAll(value);
      print('upload ${_bytes.length/_total}');
      _progress.add(((_bytes.length / _total)));
    })
      ..onDone(() async {
        _progress.add(0.0);
        print('Finish Download');
        final file = File(
            "${(await getApplicationDocumentsDirectory()).path}/$fileName");
        await file.writeAsBytes(_bytes);
        _path = file.path;
      })
      ..onError((e) async {
        print('Error Download, $e');
        _progress.add(-1.0);
        _error = e.toString();
      });
  }

  cancel()async{
    client?.close();
    await dlulStream?.cancel();
    _progress?.close();
  }
}