import 'package:get/get.dart';
import 'package:mypoint_flutter_app/base/restful_api_viewmodel.dart';
import 'package:mypoint_flutter_app/networking/restful_api_request.dart';
import 'package:mypoint_flutter_app/shared/router_gage.dart';
import '../../base/base_response_model.dart';
import '../../configs/constants.dart';
import '../../model/update_response_model.dart';
import '../../preference/data_preference.dart';
import '../main_tab_screen/main_tab_screen.dart';
import '../onboarding/onboarding_screen.dart';
import 'package:url_launcher/url_launcher.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 (!(await DataPreference.instance.logged)) {
      Get.toNamed(onboardingScreen);
      return;
    }
    showLoading();
    client.getUserProfile().then((value) async {
      hideLoading();
      final userProfile = value.data;
      if (value.isSuccess && userProfile != null) {
        await DataPreference.instance.saveUserProfile(userProfile);
        Get.toNamed(mainScreen);
      } else {
        DataPreference.instance.clearLoginToken();
        Get.toNamed(onboardingScreen);
      }
    });
  }
}

class EmptyCodable {
  EmptyCodable.fromJson(dynamic json);

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