import 'dart:io';

import 'package:dartin/dartin.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/bean/UpdateInfo.dart';
import 'package:sport/services/api/resp.dart';
import 'package:sport/services/api/rest_client.dart';
import 'package:sport/widgets/dialog/alert_dialog.dart';
import 'package:url_launcher/url_launcher.dart';

updateApp(BuildContext context) async {
  if (Platform.isAndroid) {
    updateApk(context);
  }
}

updateApk(BuildContext context) async {
  SharedPreferences prefs = await SharedPreferences.getInstance();
  String token = prefs.getString("token");
  if (token?.isEmpty == true) return;

  String version = (await PackageInfo.fromPlatform()).version;
  final api = inject<RestClient>();
  RespData<UpdateInfo> data = await api.checkUpdate(version).catchError((err) {});
  if (data.code == 0) {
    UpdateInfo info = data.data;
    if (!info.needUpdate) {
      return;
    }
    if (await showDialog(
          context: context,
          builder: (context) => CustomAlertDialog(
              title: '发现新版本 ${info.lastVersion.version}',
              child: Container(
                  width: double.infinity,
                  padding: const EdgeInsets.symmetric(horizontal: 24.0),
                  child: Text(
                    "${info.lastVersion.detail}",
                    style: TextStyle(fontSize: 14, color: Color(0xff333333), height: 1.4),
                  )),
              textOk: '立即更新',
              ok: () => Navigator.of(context).pop(true)),
        ) ==
        true) {
      launch(info.lastVersion.downloadUrl);
    }
  }
}
