watch_theme_controller.dart 2.43 KB
import 'package:doublefeel_flutter/app/routes/app_pages.dart';
import 'package:doublefeel_flutter/core/network/api/theme_api.dart';
import 'package:doublefeel_flutter/core/result/app_result.dart';
import 'package:get/get.dart';

import '../models/watch_theme_models.dart';

class WatchThemeController extends GetxController {
  WatchThemeController(this._themeApi);

  final ThemeApi _themeApi;

  final activeThemeId = RxnInt();
  final hasCustomThemes = false.obs;
  final isPremium = false.obs;
  final isLoadingThemes = false.obs;
  final officialThemeItems = <WatchThemeItem>[].obs;
  final customThemeItems = <WatchThemeItem>[].obs;

  @override
  void onInit() {
    super.onInit();
    final args = Get.arguments;
    if (args is Map) {
      hasCustomThemes.value = args['hasCustomThemes'] == true;
      isPremium.value = args['isPremium'] == true || hasCustomThemes.value;
    }
    loadThemeList();
  }

  Future<void> loadThemeList() async {
    isLoadingThemes.value = true;
    final themeListFuture = _themeApi.getThemeList(errorHandlingPolicy: null);
    final activeThemeFuture =
        _themeApi.getCurrentTheme(errorHandlingPolicy: null);
    final result = await themeListFuture;
    final activeResult = await activeThemeFuture;
    isLoadingThemes.value = false;

    if (activeResult case AppSuccess<WatchThemeItem>(data: final theme)) {
      activeThemeId.value = theme.id;
    } else {
      activeThemeId.value = null;
    }

    if (result is! AppSuccess<WatchThemeResponse>) {
      return;
    }

    final themes = result.data.themes;
    final official = themes.where((theme) => theme.isOfficialTheme).toList();
    final custom = themes.where((theme) => theme.isCustomTheme).toList();
    officialThemeItems.assignAll(official);
    customThemeItems.assignAll(custom);
    hasCustomThemes.value = custom.isNotEmpty;
    isPremium.value = isPremium.value || hasCustomThemes.value;
  }

  void executeBackLogic() {
    Get.back();
  }

  Future<void> selectOfficialTheme(int index) async {
    await Get.toNamed(Routes.WATCH_THEME_PREVIEW, arguments: {
      'theme': officialThemeItems[index],
    });
    await loadThemeList();
  }

  Future<void> createCustomTheme() async {
    await Get.toNamed(Routes.WATCH_THEME_CREATE);
    await loadThemeList();
  }

  Future<void> previewCustomTheme(WatchThemeItem theme) async {
    await Get.toNamed(Routes.WATCH_THEME_CUSTOM_PREVIEW, arguments: {
      'theme': theme,
    });
    await loadThemeList();
  }
}