import 'dart:io';
import 'package:package_info/package_info.dart';
import 'package:road24_mobile/my_app.dart';
import 'package:url_launcher/url_launcher.dart';
import '../utils/check_internet.dart';
import 'http/ApiRequest.dart';

enum VersionType { NONE, SMALL, MEDIUM, LARGE }

class VersionUpdate {
  static Future<String?> _getVersion(String os) async {
    try {
      var response = await doGetRequest("settings/$os/");

      return response?.data['results'][0]['version'];
    } catch (ex) {
      print("get version error $ex");
      return null;
    }
  }

  static Future<VersionType?> updateType() async {
    if (!await CheckInternet.isInternet()) {
      MyApp.hasInternet.value = false;
    } else {
      String os = 'ios_version';

      if (Platform.isAndroid) os = 'android_version';

      try {
        final packageInfo = await PackageInfo.fromPlatform();
        String version = packageInfo.version.replaceAll('.', ',');

        var newVersion = await _getVersion(os);

        if (newVersion != null) {
          newVersion = newVersion.replaceAll('.', ',');

          print("current version $version");
          print("remote config version $newVersion");

          final versionList = version.split(RegExp(','));

          final newVersionList = newVersion.split(RegExp(','));

          if (int.parse(versionList[0]) < int.parse(newVersionList[0]))
            return VersionType.LARGE;
          else if (int.parse(versionList[0]) > int.parse(newVersionList[0]))
            return VersionType
                .NONE; //yangi versiya dastlabki versiyasidan kichik
          //Example: current: 0.5.0, newVersion: 0.4.9. O'zgarish yo'q deb ketadi

          if (int.parse(versionList[1]) < int.parse(newVersionList[1])) {
            return VersionType.MEDIUM;
          } else if (int.parse(versionList[1]) > int.parse(newVersionList[1])) {
            return VersionType.NONE;
          }
          if (int.parse(versionList[2]) < int.parse(newVersionList[2])) {
            return VersionType.SMALL;
          }
          return VersionType.NONE;
        }
      } catch (e) {
        print('REMOTE_CONFIG_ERROR: $e');
        // if (e.toString().contains("SocketException")) {
        //   MyApp.hasInternet.value = false;
        // } else
        throw Exception(e);
      }
    }
  }

  static Future<void> launchStore() async {
    String appUrl =
        'https://apps.apple.com/uz/app/road24-jarimalar-tekshirish/id1543010525';

    if (Platform.isAndroid)
      appUrl =
          'https://play.google.com/store/apps/details?id=uz.kashapp.road24jarimalar';

    await launch(appUrl);
  }
}
