import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:farm_tpf/presentation/screens/codes/bloc/stamp_bloc.dart';
import 'package:farm_tpf/presentation/screens/codes/models/stamp_timeline.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';

import '../../../../data/api/app_exception.dart';
import '../../../../data/api/dio_provider.dart';
import '../../../../data/repository/repository.dart';
import '../../../../utils/const_common.dart';
import '../../../../utils/utils.dart';
import '../../../custom_widgets/widget_utils.dart';
import '../models/stamp.dart';

part 'detail_stamp_state.dart';

class DetailStampCubit extends Cubit<DetailStampState> {
  final repository = Repository();
  DetailStampCubit() : super(DetailStampInitial());
  static String pathDownload = 'download';
  String currentLocalPath = '';

  Future<void> preparedData(int stampId) async {
    try {
      await Future.delayed(const Duration(seconds: 0));
      emit(DetailStampLoading());
      var stamp = await repository.getStampDetail(id: stampId);
      var timeline = await repository.getStampTimeline(stampId: stampId);
      emit(DetailStampSuccessful(stamp, timeline));
    } catch (e) {
      emit(DetailStampFailure(AppException.handleError(e)));
    }
  }

  Future<void> updateStampStatus({
    required int stampId,
    required String status,
  }) async {
    UtilWidget.showLoading();
    await repository.updateStampStatus(
      (success) {
        UtilWidget.hideDialog();
        Utils.showSnackBarSuccess();
        preparedData(stampId);
      },
      (errorMessage) {
        UtilWidget.hideDialog();
        Utils.showSnackBarError();
      },
      stampId: stampId,
      status: status,
    );
  }

  Future downloadFile(String stampCode) async {
    try {
      var dio = DioProvider();
      print(DateTime.now().millisecondsSinceEpoch);
      var fileName = '${DateTime.now().millisecondsSinceEpoch.toString()}.xlsx';

      currentLocalPath = await getFilePath(fileName);
      UtilWidget.showLoading();
      await dio.download(
        '${ConstCommon.baseUrl}/api/tb-codes/export?tbCodeValue=$stampCode',
        currentLocalPath,
        onReceiveProgress: (rec, total) {},
      );
      UtilWidget.hideDialog();
      await onOpenFile();
    } catch (e) {
      UtilWidget.hideDialog();
      Utils.showSnackBarError(message: 'Không thể mở tập tin');
      print(e.toString());
    }
  }

  Future<void> onOpenFile() async {
    var result = await OpenFilex.open(currentLocalPath);
    if (result.type == ResultType.done) {
      //can open
    } else {
      Utils.showSnackBarError(message: 'Không thể mở tập tin');
    }
  }

  Future<String> getFilePath(uniqueFileName) async {
    var dir = await getApplicationDocumentsDirectory();
    var path = '${dir.path}/$pathDownload/$uniqueFileName';
    print(path);
    return path;
  }
}
