import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:meta/meta.dart';
import 'package:zhiying_base_widget/pages/message_settings_page/bloc/message_settings_repository.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'message_settings_event.dart';
import 'message_settings_state.dart';

class MessageSettingsBloc extends Bloc<MessageSettingsEvent, MessageSettingsState> {
  @override
  MessageSettingsState get initialState => MessageSettingsInitial();
  MessageSettingsRepository repository;

  MessageSettingsBloc(this.repository);

  @override
  Stream<MessageSettingsState> mapEventToState(
    MessageSettingsEvent event,
  ) async* {

    /// 初始化
    if (event is MessageSettingsInitEvent) {
      yield* _mapInitEventToState(event);
    }

    /// 跟新
    if (event is MessageSettingsUpdateEvent) {
      yield* _mapUpdateEventToState(event);
    }
  }

  /// 初始化
  Stream<MessageSettingsState> _mapInitEventToState(MessageSettingsInitEvent event) async* {
    /// 1、父页面数据
    var parentStyleData = await repository.fetchParentStyleData(event?.data);
    var result = await repository.fetchNetData();
    if (!EmptyUtil.isEmpty(parentStyleData)) {
      yield MessageSettingsLoadedState(styleModel: parentStyleData, dataModel: result);
      return;
    }

    var cacheStyleData = await repository.fetchCacheStyleData(event?.data);
    if (!EmptyUtil.isEmpty(cacheStyleData)) {
      yield MessageSettingsLoadedState(styleModel: cacheStyleData, dataModel: result);
    }
    var netStyleData = await repository.fetchNetStyleData(event?.data);
    if (!EmptyUtil.isEmpty(netStyleData)) {
      yield MessageSettingsLoadedState(styleModel: netStyleData, dataModel: result);
    } else {
      yield MessageSettingsErrorState();
    }
  }

  /// 更新值
  Stream<MessageSettingsState> _mapUpdateEventToState(MessageSettingsUpdateEvent event) async* {
    var styleModel = repository.getStyleModel();
    var dataModel = await repository.updateData(key: event.key, value: event.value);
    if (!EmptyUtil.isEmpty(styleModel) && !EmptyUtil.isEmpty(dataModel)) {
      yield MessageSettingsLoadedState(dataModel: dataModel, styleModel: styleModel);
    } else {
      yield MessageSettingsUpdateErrorState();
    }
  }
}
