using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Diagnostics;
using System.Text;

namespace OCR
{
    public partial class TextRecognition : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {


        }

        static string responsetext;
        static string responsehandwritting;
        static string Subscriptionkey()
        {
            return System.Configuration.ConfigurationManager
               .AppSettings["Subscription-Key"];
        }
        static string RequestParameters()
        {
            return System.Configuration.ConfigurationManager
               .AppSettings["RequestParameters"];
        }

        static string ReadURI()
        {
            return System.Configuration.ConfigurationManager
               .AppSettings["APIuri"];
        }
        static string Contenttypes()
        {
            return System.Configuration.ConfigurationManager
               .AppSettings["Contenttypes"];
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            MyTestBox.Text = JsonPrettyPrint(responsetext);
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string fileName = System.IO.Path.GetFileName
               (MyFileUpload.PostedFile.FileName);
            MyFileUpload.PostedFile.SaveAs(Server.MapPath
               ("~/images/" + fileName));
            MyImage.ImageUrl = "~/images/" + fileName;
            var path = Server.MapPath(@"~/images/" + fileName);
            CallAPIforOCR(path);
            //ReadHandwritttingFromImage(path);
            MyTestBox.Text = JsonPrettyPrint(responsetext);


        }
        static byte[] GetByteArray(string LocalimageFilePath)
        {
            FileStream ImagefileStream = new
               FileStream(LocalimageFilePath, FileMode.Open,
               FileAccess.Read);
            BinaryReader ImagebinaryReader = new
               BinaryReader(ImagefileStream);
            return ImagebinaryReader.ReadBytes((int)
               ImagefileStream.Length);
        }
        // Optical Character Reader
        static async void CallAPIforOCR(string LocalimageFilePath)
        {
            var ComputerVisionAPIclient = new HttpClient();

            try
            {
               
                ComputerVisionAPIclient.DefaultRequestHeaders
                   .Add("Ocp-Apim-Subscription-Key",
                   Subscriptionkey());
                string requestParameters = RequestParameters();
                string APIuri = ReadURI() + requestParameters;
                
                HttpResponseMessage myresponse;
                
                byte[] byteData = GetByteArray(LocalimageFilePath);
                var content = new ByteArrayContent(byteData);

                content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

                // Execute the REST API call.
                myresponse = await ComputerVisionAPIclient.PostAsync(APIuri, content);
                myresponse.EnsureSuccessStatusCode();
               

                responsetext = await myresponse.Content
                   .ReadAsStringAsync();
                
            }

            catch (Exception e)
            {
                EventLog.WriteEntry("Text Recognition Error",
                   e.Message + "Trace" + e.StackTrace,
                   EventLogEntryType.Error, 121, short.MaxValue);
            }
        }



        static async void ReadHandwritttingFromImage(string LocalimageFilePath)
        {
            HttpResponseMessage myresponse = null;
            IEnumerable<string> myresponseValues = null;
            string operationLocation = null;

            var ComputerVisionAPIclient = new HttpClient();
            ComputerVisionAPIclient.DefaultRequestHeaders.Add
               ("Ocp-Apim-Subscription-Key", Subscriptionkey());
            string requestParameters = RequestParameters();
            string APIuri = ReadURI() + requestParameters;



            byte[] byteData = GetByteArray(LocalimageFilePath);
            var content = new ByteArrayContent(byteData);

            content.Headers.ContentType = new
               MediaTypeHeaderValue(Contenttypes());

            try
            {
                myresponse = await ComputerVisionAPIclient
                   .PostAsync(APIuri, content);
                myresponseValues = myresponse.Headers
                   .GetValues("Operation-Location");
            }
            catch (Exception e)
            {
                EventLog.WriteEntry("Handwritting Recognition Error",
                   e.Message + "Trace" + e.StackTrace,
                   EventLogEntryType.Error, 121, short.MaxValue);
            }

            foreach (var value in myresponseValues)
            {
                operationLocation = value;
                break;
            }

            try
            {
                myresponse = await ComputerVisionAPIclient
                   .GetAsync(operationLocation);
                responsehandwritting = await myresponse.Content
                   .ReadAsStringAsync();
                responsetext= responsehandwritting;
            }
            catch (Exception e)
            {
                EventLog.WriteEntry("Handwritting Recognition Error",
                   e.Message + "Trace" + e.StackTrace,
                   EventLogEntryType.Error, 121, short.MaxValue);
            }
        }


        static string JsonPrettyPrint(string json)
        {
            if (string.IsNullOrEmpty(json))
                return string.Empty;

            json = json.Replace(Environment.NewLine, "").Replace("\t", "");

            StringBuilder sb = new StringBuilder();
            bool quote = false;
            bool ignore = false;
            int offset = 0;
            int indentLength = 3;

            foreach (char ch in json)
            {
                switch (ch)
                {
                    case '"':
                        if (!ignore) quote = !quote;
                        break;
                    case '\'':
                        if (quote) ignore = !ignore;
                        break;
                }

                if (quote)
                    sb.Append(ch);
                else
                {
                    switch (ch)
                    {
                        case '{':
                        case '[':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', ++offset * indentLength));
                            break;
                        case '}':
                        case ']':
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', --offset * indentLength));
                            sb.Append(ch);
                            break;
                        case ',':
                            sb.Append(ch);
                            sb.Append(Environment.NewLine);
                            sb.Append(new string(' ', offset * indentLength));
                            break;
                        case ':':
                            sb.Append(ch);
                            sb.Append(' ');
                            break;
                        default:
                            if (ch != ' ') sb.Append(ch);
                            break;
                    }
                }
            }

            return sb.ToString().Trim();
        }
    }
}