using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using dodohold.core;
using System.Xml.Linq;
using YunhuiKit;
using System.Text.Json;
using COSXML.Network;

using molilian.core.PushDataReport;

namespace molilian.core
{

    public class PushDataReportPush
    {
        private string _url = "https://adx.ads.heytapmobi.com";
        private string _app_key = "mll";
        private string _app_secret = "fHTPd7RK7OnpIv7zGvPgL2Wv8P3pDYfW";
        public PushDataReportPush()
        {
        }

        public PushDataReportPush(string url, string app_key, string app_secret)
        {
            _url = url;
            _app_key = app_key;
            _app_secret = app_secret;
        }

        public async Task<ResponseDTO> PushReportData(PushDataReportDTO item, CancellationToken cancellationToken = default)
        {
            try
            {
                var options = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    WriteIndented = true
                };
                string json = JsonSerializer.Serialize(item, options);


                var root = await Request("/cps/data/report", json, cancellationToken);
                var response = root.GetRawText().Convert2Object<ResponseDTO>();
                return response;
            }
            catch (Exception ex)
            {
                return new ResponseDTO
                {
                    code = 500,
                    message = ex.Message
                };
            }
        }

        public async Task<JsonElement> Request(string action, string post, CancellationToken cancellationToken = default)
        {
            string url = $"{_url}{action}";

            long ts = DateTime.Now.Convert2UnixTimestamp(true);
            string sign = $"{_app_key}{_app_secret}{ts}".ToSHA1();
            string token = $"{_app_key}:{ts}:{sign}".ToBase64();

            try
            {
                WebClientUtility client = new WebClientUtility();
                client.SetContentType("application/json");
                client.SetHeaders(new Dictionary<string, string> { { "Authorization", $"Bearer {token}" } });
                client.Post(post);
                var response = await client.RequestAsync(url, "POST", cancellationToken);

                if (!response.Successed)
                {
                    throw response.ResponseException;
                }
                var body = response.Body();

                await new LoggerLibrary("push_report")
                    .Info(action, post)
                    .Info(body)
                    .SaveAsync();

                var root = body.Convert2JsonElement();
                return root;
            }
            catch (Exception ex)
            {
                await new LoggerLibrary("push_report", "error")
                    .Info(action, post)
                    .Info(ex.Message, ex.StackTrace)
                    .SaveAsync();
                throw;
            }
        }


    }
}