import 'dart:io';

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:flutter/material.dart';
import 'package:health/health.dart';

class syncHealthDataButton extends StatefulWidget {
  syncHealthDataButton();

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

class _syncHealthDataButtonState extends State<syncHealthDataButton> {
  List<HealthDataPoint> _healthDataList = [];

  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() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultButton(TranslationBase.of(context).syncHealthData, () => readAll()).insideContainer;
  }

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

    GifLoaderDialogUtils.showMyDialog(context);
    Med_InsertTransactionsInputsList.clear();
    DateTime startDate = DateTime.now().subtract(new Duration(days: 30));

    HealthFactory health = HealthFactory();
    List<HealthDataType> types = [HealthDataType.STEPS, HealthDataType.HEART_RATE, Platform.isAndroid ? HealthDataType.DISTANCE_DELTA : HealthDataType.DISTANCE_WALKING_RUNNING];

    await health.requestAuthorization(types);

    try {
      List<HealthDataPoint> healthData = await health.getHealthDataFromTypes(startDate, DateTime.now(), types);
      _healthDataList.addAll(healthData);
    } catch (e) {
      print("Caught exception in getHealthDataFromTypes: $e");
    }

    _healthDataList = HealthFactory.removeDuplicates(_healthDataList);

    _healthDataList.forEach((x) {
      if (x.type == HealthDataType.STEPS) {
        Med_InsertTransactionsInputsList.add(
            healthData(MedCategoryID: 6, MedSubCategoryID: MedSubCategoryID, MachineDate: DateUtil.convertDateToString(x.dateFrom), Value: x.value, TransactionsListID: TransactionsListID++));
      }
      if (x.type == HealthDataType.HEART_RATE) {
        Med_InsertTransactionsInputsList.add(
            healthData(MedCategoryID: 3, MedSubCategoryID: MedSubCategoryID, MachineDate: DateUtil.convertDateToString(x.dateFrom), Value: x.value, TransactionsListID: TransactionsListID++));
      }
      if (x.type == HealthDataType.DISTANCE_DELTA || x.type == HealthDataType.DISTANCE_WALKING_RUNNING) {
        Med_InsertTransactionsInputsList.add(
            healthData(MedCategoryID: 7, MedSubCategoryID: MedSubCategoryID, MachineDate: DateUtil.convertDateToString(x.dateFrom), Value: x.value, TransactionsListID: TransactionsListID++));
      }
    });

    getAllHealthDataLists();
  }

  void getAllHealthDataLists() {
    var totalSteps = 0.0;
    var totalDistance = 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;
          totalDistance += (element['Value'] * 0.001);
        } else if (element['MedCategoryID'] == 3) {
          MedCategoryID = 3;
          counter++;
          totalHeartRate += element['Value'];
        } else if (element['MedCategoryID'] == 4) {
          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++));
        }
      });

      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;
    }
  }
}
