using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace MeterVision.Upgrade
{
    public class UpgradeHelper
    {
        //升级包所在的位置
        public const string UpgradeUrl = @"https://www.xzeai.com:6090/download/upgrade/MeterVision_app/";


        public static UpgradeModel ReadUpdateTxt1()
        {
            string updateTxtUrl = Path.Combine(UpgradeUrl, "upgrade.txt");
            try
            {
                WebClient wc = new WebClient();
                wc.Headers.Add("Accept-Charset", "utf-8");
                byte[] buffer = wc.DownloadData(updateTxtUrl);
                string res = Encoding.UTF8.GetString(buffer);
                    //Encoding.UTF8.GetString(buffer);
                Console.WriteLine(res);
                UpgradeModel upgradeModel = UpgradeModel.ParseModel(res);
                if (upgradeModel == null)
                {
                    throw new InvalidOperationException("无法读正常读取升级信息。");
                }
                return upgradeModel;
            }
            catch (WebException ex)
            {
                //ex.Message = "远程服务器返回错误: (404) 未找到。"
                Console.WriteLine(ex.Message);
                throw new InvalidOperationException("无法读取升级信息。");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new InvalidOperationException($"读取升级包错误{e.Message}。");
            }
        }

        public static UpgradeModel ReadUpdateTxt()
        {
            string updateTxtUrl = Path.Combine(UpgradeUrl, "upgrade.txt");
            try
            {
                // 使用 HttpClient 代替 WebClient
                using (HttpClient client = new HttpClient())
                {
                    // 异步请求并获取响应
                    HttpResponseMessage response = client.GetAsync(updateTxtUrl).Result;
                    // 如果请求失败，抛出异常
                    if (!response.IsSuccessStatusCode)
                    {
                        throw new InvalidOperationException($"无法读取升级信息，HTTP 错误：{response.StatusCode}");
                    }

                    // 获取响应内容并转换为字符串，注意这里可以指定编码
                    string res = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(res);

                    // 调用解析方法，转换为模型
                    UpgradeModel upgradeModel = UpgradeModel.ParseModel(res);

                    // 校验解析是否成功
                    if (upgradeModel == null || string.IsNullOrEmpty(upgradeModel.VersionCode) || string.IsNullOrEmpty(upgradeModel.ApkName))
                    {
                        throw new InvalidOperationException("升级信息格式错误或缺失必要数据。");
                    }

                    return upgradeModel;
                }
            }
            catch (WebException ex)
            {
                // 提供更多的详细错误信息
                Console.WriteLine($"WebException: {ex.Message}");
                throw new InvalidOperationException($"无法读取升级信息，错误: {ex.Message}");
            }
            catch (HttpRequestException ex)
            {
                // 针对 Http 请求的异常做进一步处理
                Console.WriteLine($"HttpRequestException: {ex.Message}");
                throw new InvalidOperationException($"无法从服务器获取数据，错误: {ex.Message}");
            }
            catch (Exception e)
            {
                // 捕获其他未知异常
                Console.WriteLine($"Exception: {e.Message}");
                throw new InvalidOperationException($"读取升级包错误：{e.Message}");
            }
        }


        public static string GetCurrentVersion()
        {
            // 获取当前应用的版本号，返回格式为 "1006"
            var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            return version.ToString();
        }


        public static bool IsNewVersionAvailable(string currentVersion, string serverVersion)
        {
            var current = new Version(currentVersion);
            var server = new Version(serverVersion);

            return server.CompareTo(current) > 0; // 如果服务器版本大于当前版本，则返回 true
        }
        //--------------------------------------------
    }
}
