import "package:collection/collection.dart";
import 'package:hmg_patient_app/core/enum/filter_type.dart';
import 'package:hmg_patient_app/core/enum/viewstate.dart';
import 'package:hmg_patient_app/core/model/radiology/final_radiology.dart';
import 'package:hmg_patient_app/core/service/medical/radiology_service.dart';
import 'package:hmg_patient_app/models/Authentication/authenticated_user.dart';
import 'package:hmg_patient_app/uitl/app_toast.dart';

import '../../../locator.dart';
import '../base_view_model.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 RadiologyViewModel extends BaseViewModel {
  FilterType filterType = FilterType.Clinic;
  RadiologyService _radiologyService = locator<RadiologyService>();

  List<FinalRadiologyList> _finalRadiologyListClinic = [];
  List<FinalRadiologyList> _finalRadiologyListHospital = [];

  List<FinalRadiologyList> get finalRadiologyList => filterType == FilterType.Clinic ? _finalRadiologyListClinic : _finalRadiologyListHospital;

  bool _isRadiologyVIDAPlus = false;

  bool get isRadiologyVIDAPlus => _isRadiologyVIDAPlus;

  String get radReportPDF => _radiologyService.radReportPDF;

  void getPatientRadOrders() async {
    setState(ViewState.Busy);
    await _radiologyService.getPatientRadOrders();
    _isRadiologyVIDAPlus = _radiologyService.isRadiologyVIDAPlus;
    if (_radiologyService.hasError) {
      error = _radiologyService.error!;
      setState(ViewState.Error);
    } else {
      //Clinic Sorting
      var clinicMap = groupBy(_radiologyService.finalRadiologyList, (FinalRadiology obj) => obj.clinicDescription);
      clinicMap.forEach((key, value) {
        _finalRadiologyListClinic.add(FinalRadiologyList(filterName: key, finalRadiologyList: value.toList()));
      });

      //Hospital Sorting
      var hospitalMap = groupBy(_radiologyService.finalRadiologyList, (FinalRadiology obj) => obj.projectName);
      hospitalMap.forEach((key, value) {
        _finalRadiologyListHospital.add(FinalRadiologyList(filterName: key, finalRadiologyList: value.toList()));
      });

      setState(ViewState.Idle);
    }
  }

  String get radImageURL => _radiologyService.url;

  getRadImageURL({required int invoiceNo, String? invoiceType, required int lineItem, required int projectId, required bool isVidaPlus, required String examId}) async {
    setState(ViewState.Busy);
    await _radiologyService.getRadImageURL(invoiceNo: invoiceNo, invoiceType: invoiceType, lineItem: lineItem, projectId: projectId, isVidaPlus: isVidaPlus, examId: examId);
    if (_radiologyService.hasError) {
      error = _radiologyService.error!;
      setState(ViewState.Error);
    } else
      setState(ViewState.Idle);
  }

  sendRadReportEmail({required FinalRadiology finalRadiology, required String mes, required AuthenticatedUser userObj, required isDownload}) async {
    setState(ViewState.BusyLocal);
    await _radiologyService.sendRadReportEmail(finalRadiology: finalRadiology, userObj: userObj, isDownload: isDownload);
    if (_radiologyService.hasError) {
      error = _radiologyService.error!;
      AppToast.showErrorToast(message: error);
    } else {
      if (isDownload) {
        if (radReportPDF.isNotEmpty) {
          String path = await _createFileFromString(radReportPDF, "pdf");
          try {
            OpenFilex.open(path);
          } catch (ex) {
            AppToast.showErrorToast(message: "Cannot open file.");
          }
        }
      } else {
        AppToast.showSuccessToast(message: mes);
      }
      // AppToast.showSuccessToast(message: mes);
    }
    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;
  }

  setFilterType(FilterType filterType) {
    this.filterType = filterType;
    notifyListeners();
  }
}
