import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/restful_api_viewmodel.dart';
import 'package:mypoint_flutter_app/networking/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import '../../base/base_response_model.dart';
import '../../model/auth/profile_response_model.dart';
import 'models/update_response_model.dart';
import '../../preference/data_preference.dart';
import '../../preference/point/point_manager.dart';
import 'package:url_launcher/url_launcher.dart';
import '../popup_manager/popup_manager_viewmodel.dart';

class SplashScreenViewModel extends RestfulApiViewModel {
  var infoAppUpdate = BaseResponseModel<UpdateResponseModel>().obs;
  var isLoading = false.obs;

  void checkUpdateApp() {
    showLoading();
    isLoading(true);
    client.checkUpdateApp().then((value) {
      infoAppUpdate.value = value;
      hideLoading();
      isLoading(false);
    });
  }

  Future<void> openLink() async {
    final updateLink = infoAppUpdate.value.data?.updateRequest?.first?.updateLink ?? "";
    if (updateLink.isEmpty) return;
    final Uri url = Uri.parse(updateLink);
    if (await canLaunchUrl(url)) {
      await launchUrl(url);
    }
  }

  Future<void> getUserProfile() async {
    if (!(DataPreference.instance.logged)) {
      Get.toNamed(onboardingScreen);
      return;
    }
    showLoading();
    client.getUserProfile().then((value) async {
      hideLoading();
      final userProfile = value.data;
      if (value.isSuccess && userProfile != null) {
        _freshDataAndToMainScreen(userProfile);
      } else {
        DataPreference.instance.clearLoginToken();
        Get.toNamed(onboardingScreen);
      }
    });
  }

  void _freshDataAndToMainScreen(ProfileResponseModel userProfile) async {
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await DataPreference.instance.saveUserProfile(userProfile);
      await UserPointManager().fetchUserPoint();
      await PopupManagerViewModel.instance.ensureLoaded();
      Get.toNamed(mainScreen);
    });
  }
}

class EmptyCodable {
  EmptyCodable.fromJson(dynamic json);

  Map<String, dynamic> toJson() {
    return {};
  }
}
