import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:road24_mobile/data/http/GeneralRequest.dart';
import 'package:road24_mobile/data/repository/FinesDirectusRepository.dart';
import 'package:road24_mobile/data/repository/FinesRepository.dart';
import 'package:road24_mobile/data/response/FinesResponse.dart';
import 'package:road24_mobile/data/response/manual_part/fines/FinesManualResponse.dart';
import 'package:road24_mobile/model/mixins/FinesManualMixin.dart';
import 'package:road24_mobile/view/manual/parts/fines/fines_manual.dart';
import 'package:road24_mobile/view/mycar/fines/fines_page.dart';

part 'fines_event.dart';

part 'fines_state.dart';

class FinesBloc extends Bloc<FinesEvent, FinesState> {
  final FinesRepository repository;

  FinesBloc({required this.repository}) : super(FinesInitial());

  @override
  Stream<FinesState> mapEventToState(FinesEvent event) async* {
    if (event is GetFines) {
      try {
        yield FinesInitial();
        final dynamic response = await repository.getFines(
          carId: event.carId,
          types: event.types,
          pageSize: event.pageSize,
          pageNumber: event.pageNumber,
        );
        if (event.types.contains(1)) {
          yield NotPaidFinesListSuccessState(
              response: Fines.fromJson(response));
        } else if (event.types.contains(2)) {
          yield HistoryFinesListSuccessState(
              response: Fines.fromJson(response));
        }
      } catch (e) {
        print("fine exception: $e");
        yield FinesFail(exception: e);
      }
    }

    if (event is GetFineDetails) {
      try {
        yield FinesInitial();

        final dynamic response = await repository.getFineById(event.id);

        var details = FineDetails.fromJson(response);

        try {
          if (details.pSeryNumber.startsWith("RR")) {
            var url = "https://video.yhxbb.uz/api/r/${details.pSeryNumber}";

            var res = await GeneralRequest.getRequest(url);

            var carNumber = res["offense"]["vehicle_id_img"];

            var carImage = res["offense"]["vehicle_img"];

            var report = res["offense"]["report"];

            var videoUrl = report["video"]["url"];

            var extraVideo = report["extra_video"];

            String? extraVideoUrl;

            if (extraVideo != null) {
              extraVideoUrl = extraVideo["url"];

              details.extraVideoLink = extraVideoUrl;
            }

            var lat = report["lat"];

            var long = report["lng"];

            details.videoLink = videoUrl;

            details.latitude = lat;

            details.longitude = long;

            details.plateNumber = FineFile(file: carNumber);

            details.plateNumberAndCar = FineFile(file: carImage);
          }
        } catch (ex) {}

        yield FineDetailSuccessState(response: details);
      } catch (e) {
        print("get fines ERROR:...." + e.toString());

        yield FinesFail(exception: e);
      }
    }

    if (event is RefreshFineRemain) {
      try {
        yield FinesInitial();

        await repository.refreshFineRemain(event.id);

        FinesPage.isRefreshed = true;

        add(GetFineDetails(event.id));
      } catch (e) {
        print("refresh errr..$e");
        yield GetFinesManualFail(exception: e);
      }
    }

    if (event is GetCategories) {
      var fineRepo = FinesDirectusRepository();
      try {
        yield LoadingState();
        final dynamic categories = await fineRepo.getCategories();
        final dynamic articles = await fineRepo.getArticles();
        FinesManual.categories.clear();

        FinesManual.categories.addAll(categories);

        FinesManual.articles.clear();

        FinesManual.articles.addAll(articles);

        yield FineInfoSuccessState(categories: categories, articles: articles);
      } catch (e) {
        print("category exception: $e");
        yield GetFinesManualFail(exception: e);
      }
    }
    if (event is GetArticleParts) {
      var fineRepo = FinesDirectusRepository();
      try {
        yield LoadingState();
        final dynamic response = await fineRepo.getArticleParts(
            articleId: event.articleId, article: event.article);

        yield ArticlePartsSuccessState(articleParts: response);
      } catch (e) {
        print("article parts exception: $e");
        yield GetFinesManualFail(exception: e);
      }
    }
    if (event is GetBasicCalculationAmount) {
      try {
        yield LoadingState();
        await FinesManualMixin().getBasicCalculationAmount();

        yield BasicCalculationAmount(FinesManual.basicCalculationAmount!);
      } catch (e) {
        print("article parts exception in base amount: $e");
        yield GetFinesManualFail(exception: e);
      }
    }
  }
}
