using dodohold.core;
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;

namespace Dataoke
{
    public class DtkApp
    {
        private string _appKey = "";

        private string _appSecret = "";

        public DtkApp(string appKey, string appSecret)
        {
            if (string.IsNullOrEmpty(appKey) || string.IsNullOrEmpty(appSecret))
            {
                Console.WriteLine("AppKey 和 AppSecret 必填！");
                throw new Exception("AppKey 和 AppSecret 必填！");
            }
            _appKey = appKey;
            _appSecret = appSecret;
        }

        public string Get(string apiUrl, string version, ApiParameters parameters)
        {
            try
            {
                string url = BuildUrl(apiUrl, version, parameters);
                using HttpClient client = new HttpClient();
                HttpResponseMessage response = client.GetAsync(url).Result;
                if (response.IsSuccessStatusCode)
                {
                    Stream result2 = response.Content.ReadAsStreamAsync().Result;
                    StreamReader streamReader = new StreamReader(result2, Encoding.GetEncoding("utf-8"));
                    string result = streamReader.ReadToEnd();
                    streamReader.Close();
                    result2.Close();
                    return result;
                }
                return response.StatusCode.ToString();
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string BuildUrl(string apiUrl, string version, ApiParameters parameters)
        {
            int nonce;
            string timer;
            string sign = MakeSign(out nonce, out timer);
            if (sign == "")
            {
                return "";
            }
            string url = apiUrl.Trim() + "?appKey=" + _appKey.Trim() + "&nonce=" + nonce + "&signRan=" + sign + "&version=" + version.Trim() + "&timer=" + timer;
            if (parameters.Value.Count <= 0)
            {
                return url;
            }
            for (int i = 0; i <= parameters.Value.Count - 1; i++)
            {
                url += $"&{parameters.Value[i].Key}={parameters.Value[i].Value}";
            }
            return url;
        }

        public string MakeSign(out int nonce, out string timer)
        {
            Random rd = new Random();
            nonce = rd.Next(100000, 1000000);
            timer = GetTimeStamp();
            try
            {
                return $"appKey={_appKey}&timer={timer}&nonce={nonce}&key={_appSecret}".MD5(false, false);
            }
            catch (Exception)
            {
                return "";
            }
        }

        private static string GetTimeStamp()
        {
            return Convert.ToInt64((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalMilliseconds).ToString();
        }
    }
}
