import 'package:collection/collection.dart';
import 'package:diplomaticquarterapp/models/SmartWatch/HealthData.dart';
import 'package:diplomaticquarterapp/services/smartwatch_integration/SmartWatchIntegrationService.dart';
import 'package:diplomaticquarterapp/uitl/app_toast.dart';
import 'package:diplomaticquarterapp/uitl/date_uitl.dart';
import 'package:diplomaticquarterapp/uitl/gif_loader_dialog_utils.dart';
import 'package:diplomaticquarterapp/uitl/translations_delegate_base.dart';
import 'package:diplomaticquarterapp/widgets/buttons/defaultButton.dart';
import 'package:fit_kit/fit_kit.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';

class syncHealthDataButton extends StatefulWidget {
  double marginTop;

  double hight;

  double minWidth;

  syncHealthDataButton({this.marginTop, this.hight, this.minWidth});

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

class _syncHealthDataButtonState extends State<syncHealthDataButton> {
  List<DataType> dataTypes = List();

  List<healthData> Med_InsertTransactionsInputsList = new List();
  List<healthData> Med_InsertTransactionsInputsList2 = new List();

  List<healthData> sleepDataList = new List();

  List<healthData> healthDataList = new List();

  int TransactionsListID = 1;

  int MedCategoryID = 0;

  @override
  void initState() {
    dataTypes.add(DataType.DISTANCE);
    dataTypes.add(DataType.STEP_COUNT);
    dataTypes.add(DataType.HEART_RATE);
    // dataTypes.add(DataType.SLEEP);
    // dataTypes.add(DataType.ENERGY);

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: Padding(
        padding: const EdgeInsets.all(20.0),
        child: DefaultButton(TranslationBase.of(context).syncHealthData, () {
          print("ReadAll");
          readAll();
        }),
      ),
    );
  }

  void readAll() async {
    TransactionsListID = 1;
    var MedSubCategoryID = 0;
    double value = 0.0;

    GifLoaderDialogUtils.showMyDialog(context);
    Med_InsertTransactionsInputsList.clear();
    var date;
    var differenceInHours;
    String strDifferenceInHours;
    var differenceInMinutes;
    String strDifferenceInMinutes;
    var today = DateTime.now();
    var yearNum = DateFormat('y').format(today).toString();

    var firstDayOfTheYear = DateTime.parse(yearNum + "-" + "01" + "-" + "01");

    if (await FitKit.requestPermissions(dataTypes)) {
      for (DataType type in dataTypes) {
        final results = await FitKit.read(
          type,
          dateFrom: firstDayOfTheYear,
          dateTo: DateTime.now(),
          limit: 1000,
        );

        if (type == DataType.DISTANCE) {
          MedCategoryID = 7;
        } else if (type == DataType.STEP_COUNT) {
          MedCategoryID = 6;
        } else if (type == DataType.HEART_RATE) {
          MedCategoryID = 3;
        }

        results.forEach((result) {
          // print("in forEach");
          date = result.dateTo;
          if (result.value.runtimeType.toString() == "int") {
            value = double.parse(result.value.toString());
          } else {
            value = result.value;
          }

          MedSubCategoryID = 0;

          if (MedCategoryID == 4) {
            differenceInHours = null;
            var sleepDate = result.dateFrom.toString().substring(0, 10);

            DateTime dateFrom = result.dateFrom;
            DateTime dateTo = result.dateTo;

            differenceInMinutes = dateTo.difference(dateFrom).inMinutes;
            differenceInMinutes > 59 ? differenceInHours = differenceInMinutes / 60 : differenceInMinutes = differenceInMinutes;

            if (differenceInHours != null && differenceInHours != 0) {
              differenceInHours = differenceInHours.toInt();
              differenceInMinutes = differenceInMinutes % 60;

              differenceInHours < 10 ? strDifferenceInHours = "0" + differenceInHours.toString() : strDifferenceInHours = differenceInHours.toString();
            } else {
              strDifferenceInHours = "00";
              differenceInHours = 00;
            }
            differenceInMinutes < 10 ? strDifferenceInMinutes = "0" + differenceInMinutes.toString() : strDifferenceInMinutes = differenceInMinutes.toString();

            sleepDate = DateTime.parse(sleepDate + " " + strDifferenceInHours + ":" + strDifferenceInMinutes + ":" + "00.00").toString();
            String hours = sleepDate.substring(11, sleepDate.indexOf(":"));
            print(hours);

            String minutes = sleepDate.substring(sleepDate.indexOf(":") + 1, sleepDate.indexOf(":") + 3);
            print(minutes);

            if (value == 0 || value == 109) {
              print("in Bed");
              MedSubCategoryID = 1;
              value = double.parse(hours + "." + minutes);
              print("value");
              print(value);
            } else if (value == 1 || value == 110) {
              print("Sleep");
              MedSubCategoryID = 2;
              value = double.parse(hours + "." + minutes);
              print("value");
              print(value);
            }
          }
          date = DateUtil.convertDateToString(date);
          Med_InsertTransactionsInputsList.add(healthData(MedCategoryID: MedCategoryID, MedSubCategoryID: MedSubCategoryID, MachineDate: date, Value: value, TransactionsListID: TransactionsListID++));
        });
      }
    }
    getAllHealthDataLists();
  }

  void getAllHealthDataLists() {
    var totalSteps = 0.0;
    var totalDistance = 0.0;
    // double totalCalories = 0.0 ;
    double totalHeartRate = 0.0;
    double avgTotalHeartRate = 0.0;
    var counter = 0;
    List data = [];
    TransactionsListID = 1;

    DateTime date;
    sleepDataList.clear();

    Med_InsertTransactionsInputsList.forEach((result) {
      data.add(result.toJson());
    });

    Med_InsertTransactionsInputsList2.clear();

    var newMap = groupBy(data, (obj) => DateUtil.convertStringToDate(obj['MachineDate']).toString().substring(0, 10));

    newMap.forEach((key, value) {
      totalSteps = 0.0;
      totalDistance = 0.0;
      totalHeartRate = 0.0;
      avgTotalHeartRate = 0.0;
      counter = 0;

      date = DateTime.parse(key);

      value.forEach((element) {
        if (element['MedCategoryID'] == 6) {
          MedCategoryID = 6;

          totalSteps += element['Value'];
        } else if (element['MedCategoryID'] == 7) {
          MedCategoryID = 7;
          // to convert from meter to km
          totalDistance += (element['Value'] * 0.001);
        } else if (element['MedCategoryID'] == 3) {
          // print("HeartRate");
          MedCategoryID = 3;
          counter++;
          totalHeartRate += element['Value'];
        } else if (element['MedCategoryID'] == 4) {
          print("sleeeeep");
          sleepDataList.add(new healthData(
              MedCategoryID: 4, MedSubCategoryID: element['MedSubCategoryID'], MachineDate: DateUtil.convertDateToString(date), Value: element['Value'], TransactionsListID: TransactionsListID++));

          Med_InsertTransactionsInputsList2.add(new healthData(
              MedCategoryID: 4, MedSubCategoryID: element['MedSubCategoryID'], MachineDate: DateUtil.convertDateToString(date), Value: element['Value'], TransactionsListID: TransactionsListID++));
        }
        // else if(element['MedCategoryID'] == 8){
        //
        //   totalCalories += element['Value'] ;
        // }
      });

      if (counter == 0) {
        counter = 1;
      }
      if (totalHeartRate == 0) {
        avgTotalHeartRate = 0;
      } else {
        avgTotalHeartRate = totalHeartRate / counter;
      }

      Med_InsertTransactionsInputsList2.add(
          new healthData(MedCategoryID: 6, MedSubCategoryID: 0, MachineDate: DateUtil.convertDateToStringLocation(date), Value: totalSteps, TransactionsListID: TransactionsListID++));
      Med_InsertTransactionsInputsList2.add(
          new healthData(MedCategoryID: 7, MedSubCategoryID: 0, MachineDate: DateUtil.convertDateToStringLocation(date), Value: totalDistance, TransactionsListID: TransactionsListID++));
      Med_InsertTransactionsInputsList2.add(
          new healthData(MedCategoryID: 3, MedSubCategoryID: 0, MachineDate: DateUtil.convertDateToStringLocation(date), Value: avgTotalHeartRate, TransactionsListID: TransactionsListID++));
    });

    addInsertTransactionsInputsList();

    GifLoaderDialogUtils.hideDialog(context);
  }

  addInsertTransactionsInputsList() {
    if (Med_InsertTransactionsInputsList2.isNotEmpty) {
      GifLoaderDialogUtils.showMyDialog(context);
      SmartWatchIntegrationService service = new SmartWatchIntegrationService();
      service.insertPatientHealthData(Med_InsertTransactionsInputsList2, context).then((res) {
        GifLoaderDialogUtils.hideDialog(context);
        AppToast.showSuccessToast(message: TranslationBase.of(context).syncSuccess);
      }).catchError((err) {
        GifLoaderDialogUtils.hideDialog(context);
        print(err);
      });
    } else {
      return;
    }
  }
}
