using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using System.Net;
using System.Text;
using Sign;
using UtilsHelper;

namespace HWOcrClientAkSk
{
    /*
     OCR Client authenticated by AKSK

    initializd by ak,sk,endpoint

    Attributes:
        ak: Access key for ocr user
        sk: Secret key for ocr user
        httpendpoint:httpendpoint for the ocr request
     */
    class HWOcrClientAKSK
    {
        private readonly Signer sig = new Signer();
        private readonly string httpSchema = "https";
        private readonly string httpMethod = "POST";
        private string endPoint = "";

        public HWOcrClientAKSK()
        {

        }
        public HWOcrClientAKSK(string ak, string sk, string httpEndPoint)
        {
            if (ak == null || sk == null || httpEndPoint == null)
            {
                throw new Exception("The parameter for HWOcrClientAKSK cannot be empty");
            }
            sig.appKey = ak;
            sig.appSecret = sk;
            endPoint = httpEndPoint;
        }

        #region ocr request to recognise image
        /*
        <summary>
        ocr recognise image
        </summary>
        <param name = "uri" > api </ param >
        <param name="filepath">imagePath</param>
        <param name = "options" > the params of the request</param>
        <returns>the statusCode of request</returns>
        **/
        public HttpWebResponse RequestOcrAkSkService(string uri, string imgPath, Dictionary<string, Object> options)
        {
            if (uri == "" || imgPath == "")
            {
                throw new Exception("The parameter for requestOcrAkSkService cannot be empty");
            }

            Request request = new Request();
            request.scheme = httpSchema;
            request.host = endPoint;
            request.method = httpMethod;
            request.uri = uri;
            request.headers.Add("Content-Type", "application/json");

            Dictionary<string, Object> payload = new Dictionary<string, Object>();
            if (imgPath.Contains("http://") || imgPath.Contains("https://"))
            {
                payload.Add("url", imgPath);
            }
            else
            {
                //image base64 encode
                Utils utils = new Utils();
                string strbaser64 = utils.ImgToBase64String(imgPath);
                if(strbaser64 != null)
                {
                    payload.Add("image", strbaser64);
                }
            }

            if (options != null)
            {
                foreach (var item in options)
                {
                    if (!payload.ContainsKey(item.Key))
                    {
                        payload.Add(item.Key, item.Value);
                    }
                }
            }

            //set the request.body
            request.body = JsonConvert.SerializeObject(payload);
            sig.Sign(request);
            string url = httpSchema + "://" + endPoint + uri;

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            //set the request
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "post";
            req.ContentType = "application/json";
            req.Host = request.headers["host"];
            req.ContentLength = request.headers["content-length"].Length;
            req.Headers.Add("Authorization", request.headers["Authorization"]);
            req.Headers.Add("X-Sdk-Date", request.headers["X-Sdk-Date"]);

            byte[] data = Encoding.UTF8.GetBytes(request.body);
            req.ContentLength = data.Length;
            req.GetRequestStream().Write(data, 0, data.Length);
            req.GetRequestStream().Close();

            try
            {
                HttpWebResponse response = (HttpWebResponse)req.GetResponse();
                return response;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception caught: {0}", ex);
                return null;
            }
        }
        #endregion
    }
}
