import 'dart:async';

import 'package:bloc/bloc.dart';
import 'package:zhiying_base_widget/pages/privacy_settings_page/bloc/privacy_settings_repository.dart';
import 'privacy_settings_event.dart';
import 'privacy_settings_state.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

class PrivacySettingsBloc extends Bloc<PrivacySettingsEvent, PrivacySettingsState> {
  @override
  PrivacySettingsState get initialState => PrivacySettingsInitial();

  PrivacySettingsRepository repository;

  PrivacySettingsBloc(this.repository);

  @override
  Stream<PrivacySettingsState> mapEventToState(
    PrivacySettingsEvent event,
  ) async* {
    if (event is PrivacySettingsInitEvent) {
      yield* _mapInitEventToState(event);
    }
    if(event is PrivacySettingsUpdateEvent){
      yield* _mapUpdateEventToState(event);
    }
  }


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

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

  /// 更新值
  Stream<PrivacySettingsState>  _mapUpdateEventToState(PrivacySettingsUpdateEvent 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 PrivacySettingsLoadedState(dataModel: dataModel, model: styleModel);
    }else{
      yield PrivacySettingsUpdateErrorState();
    }

  }


}
