import 'package:bloc/bloc.dart';
import 'package:flutter/material.dart';
import 'package:hoshan/data/storage/shared_preferences_helper.dart';

class ThemeModeCubit extends Cubit<ThemeMode> {
  ThemeModeCubit() : super(_themeModeInitial());

  static ThemeMode _themeModeInitial() {
    final mode = ThemeModeStorage.getMode();
    if (mode == 'system') {
      final brightness =
          WidgetsBinding.instance.platformDispatcher.platformBrightness;
      return brightness == Brightness.dark ? ThemeMode.dark : ThemeMode.light;
    } else {
      if (mode == 'dark') {
        return ThemeMode.dark;
      } else {
        return ThemeMode.light;
      }
    }
  }

  void switchTheme() {
    final mode = ThemeModeStorage.getMode();
    if (mode == 'dark') {
      ThemeModeStorage.setMode('light');
      emit(ThemeMode.light);
    } else {
      ThemeModeStorage.setMode('dark');
      emit(ThemeMode.dark);
    }
  }

  void setDarkMode() {
    ThemeModeStorage.setMode('dark');
    emit(ThemeMode.system);
    emit(ThemeMode.dark);
  }

  void setLightkMode() {
    ThemeModeStorage.setMode('light');
    emit(ThemeMode.system);
    emit(ThemeMode.light);
  }

  void setDefaultSystem() {
    final brightness =
        WidgetsBinding.instance.platformDispatcher.platformBrightness;
    ThemeModeStorage.setMode('system');
    emit(ThemeMode.system);
    emit(brightness == Brightness.dark ? ThemeMode.dark : ThemeMode.light);
  }

  bool isDark() {
    return state == ThemeMode.dark;
  }

  String whatIsThemeMode() {
    return ThemeModeStorage.getMode();
  }
}
