import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/sick_leave/sick_leave.dart';
import 'package:hmg_patient_app/core/service/medical/PatientSickLeaveService.dart';
import 'package:hmg_patient_app/core/viewModels/base_view_model.dart';
import 'package:hmg_patient_app/locator.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';

import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';

class PatientSickLeaveViewMode extends BaseViewModel {
  PatientSickLeaveService _patientSickLeaveService = locator<PatientSickLeaveService>();

  List<SickLeave> get sickLeaveList => _patientSickLeaveService.sickLeaveList;

  String get sickLeavePDF => _patientSickLeaveService.sickLeavePDF;

  getSickLeave() async {
    setState(ViewState.Busy);
    await _patientSickLeaveService.getSickLeave();
    if (_patientSickLeaveService.hasError) {
      error = _patientSickLeaveService.error!;
      setState(ViewState.Error);
    } else {
      setState(ViewState.Idle);
    }
  }

  Future sendSickLeaveEmail(
      {required String message, required int requestNo, required String projectName, required String doctorName, required int projectID, required String setupID, required bool isDownload}) async {
    setState(ViewState.Busy);
    await _patientSickLeaveService.sendSickLeaveEmail(requestNo: requestNo, projectName: projectName, doctorName: doctorName, projectID: projectID, setupID: setupID, isDownload: isDownload);
    if (_patientSickLeaveService.hasError) {
      error = _patientSickLeaveService.error!;
      setState(ViewState.ErrorLocal);
      AppToast.showErrorToast(message: error);
    } else {
      if (isDownload) {
        if (sickLeavePDF.isNotEmpty) {
          String path = await _createFileFromString(sickLeavePDF, "pdf");
          try {
            OpenFilex.open(path);
          } catch (ex) {
            AppToast.showErrorToast(message: "Cannot open file.");
          }
        }
      } else {
        AppToast.showSuccessToast(message: message);
      }
      setState(ViewState.Idle);
    }
  }

  Future<String> _createFileFromString(String encodedStr, String ext) async {
    Uint8List bytes = base64.decode(encodedStr);
    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = File("$dir/" + DateTime.now().millisecondsSinceEpoch.toString() + "." + ext);
    await file.writeAsBytes(bytes);
    return file.path;
  }
}
