using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MeterVision.Upgrade
{
    public class UpgradeModel
    {
        public string VersionCode { get; set; }

        public string ApkName { get; set; }

        public string Updates { get; set; }


        public UpgradeModel()
        {

        }

        public static UpgradeModel ParseModel(string data)
        {
            var lines = data.Trim().Split(new[] { "\r\n", "\n" }, StringSplitOptions.None);
            var upgradeModel = new UpgradeModel();
            bool isReadingUpdates = false;

            foreach (var line in lines)
            {
                if (line.Contains("="))
                {
                    var parts = line.Split(new[] { '=' }, 2);
                    var key = parts[0].Trim();
                    var value = parts[1].Trim();

                    // 输出 key 的十六进制 ASCII 码，查看是否有隐形字符
                    Console.WriteLine($"Key: '{key}' (Hex: {BitConverter.ToString(System.Text.Encoding.ASCII.GetBytes(key))})");


                    //实际条件不成立(输出一些key的十六进制值，看看ASCII码是多少)
                    if (key.Equals("versionCode"))
                    {
                        Console.WriteLine(key);
                    }

                    //实际条件成立
                    if (key.Contains("versionCode"))
                    {
                        Console.WriteLine(key);
                    }

                    switch (key)
                    {
                        case "versionCode":
                            upgradeModel.VersionCode = value; //int.Parse(value);
                            break;
                        case "zipName":
                            upgradeModel.ApkName = value;
                            break;
                        case "updates":
                            isReadingUpdates = true;
                            break;
                    }
                }
                else if (isReadingUpdates)
                {
                    // 将 updates 后的内容直接追加到 Updates 属性
                    upgradeModel.Updates += (upgradeModel.Updates == string.Empty ? "" : Environment.NewLine) + line.Trim();
                }
            }

            // 校验是否所有必需字段都已解析
            if (string.IsNullOrEmpty(upgradeModel.VersionCode) || string.IsNullOrWhiteSpace(upgradeModel.ApkName)
                || string.IsNullOrEmpty(upgradeModel.Updates))
            {
                return upgradeModel;
            }
            
            return upgradeModel;
        }
        //------------------------------------------------
    }
}
