import 'dart:async';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/consts/event_report_id.dart';
import 'package:electronic_assistant/data/repositories/talk_repository.dart';
import 'package:get/get.dart';

import '../../../data/bean/talk_original.dart';
import '../../../data/bean/talks.dart';
import '../controller.dart';

class OriginalController extends BaseController {
  TalkController talkController = Get.find();

  final originalList = <TalkOriginal>[].obs;

  StreamSubscription? _talkStatusListener;

  @override
  void onReady() {
    super.onReady();
    _talkStatusListener =
        talkController.talkBean.value?.status.listen((status) {
      if (status == TalkStatus.analysisSuccess) {
        requestOriginal();
      }
    });
    requestOriginal();
  }

  void eventReport(String eventId, {Map<String, dynamic>? params}) {
    talkController.eventReport(eventId, params: params);
  }

  void requestOriginal() {
    if (talkController.talkBean.value?.status.value ==
        TalkStatus.analysisSuccess) {
      eventReport(EventId.event_101300);
    } else if (talkController.talkBean.value?.status.value ==
        TalkStatus.analysisFail) {
      eventReport(EventId.event_101301);
    }
    if (originalList.isNotEmpty) {
      return;
    }
    talkRepository.talkOriginal(talkController.talkBean.value?.id).then((value) {
      originalList.value = value;
    });
  }

  @override
  void onClose() {
    super.onClose();
    _talkStatusListener?.cancel();
  }
}
