using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;
using Newtonsoft;
using Newtonsoft.Json;

namespace paddleOCR
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "image files (*.jpg)|*.jpg|All files (*.*)|*.*";
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = openFileDialog.FileName;
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                string path = System.Windows.Forms.Application.StartupPath + @"\paddleOCR.py";//py文件路径
                if (string.IsNullOrEmpty(textBox1.Text))
                {
                    return;
                }
                if (string.IsNullOrEmpty(textBox3.Text))
                {
                    return;
                }
                this.Invoke(new Action(() =>
                {
                    this.textBox2.Text = StartTest(textBox3.Text, path, textBox1.Text);
                    this.label1.Text = $"elapsed:{(DateTime.Now - startTime).TotalSeconds.ToString("f2")}s";
                    try
                    {
                        Stream s = File.Open(System.Windows.Forms.Application.StartupPath + @"\ocr_result.jpg", FileMode.Open);
                        pictureBox1.Image = Bitmap.FromStream(s);
                        s.Close();
                        s.Dispose();
                    }
                    catch
                    {
                    }
                }));
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
        private Process progressTest;
        DateTime startTime;
        /// <summary>
        /// 开始检测
        /// </summary>
        /// <param name="pythonExePath">python解释器路径</param>
        /// <param name="pythonFile">python文件</param>
        /// <param name="imgPath">图像文件路径</param>
        /// <returns></returns>
        public string StartTest(string pythonExePath, string pythonFile, string imgPath)
        {
            string state = "";
            string sArguments = pythonFile + " " + imgPath;
            this.pictureBox1.Image = null;
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = pythonExePath + " ";//环境路径需要配置好
            start.Arguments = sArguments;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            start.RedirectStandardInput = true;
            start.RedirectStandardError = true;
            start.CreateNoWindow = true;
            startTime = DateTime.Now;
            using (progressTest = Process.Start(start))
            {
                state = progressTest.StandardOutput.ReadToEnd();
                progressTest.WaitForExit(30000);
                //// 异步获取命令行内容
                //progressTest.BeginOutputReadLine();
                //// 为异步获取订阅事件
                //progressTest.OutputDataReceived += new DataReceivedEventHandler(outputDataReceived);
            }
            string[] result= state.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            if (result!=null && result.Length>1)
            {
                foreach (var item in result.Reverse())
                {
                    if(item.Contains("OCR-Result:"))
                    {
                        var ocrR=item.Substring(12);
                        if(!string.IsNullOrEmpty(ocrR))
                        {
                            var lst = DeserializeJsonToList<string>(ocrR);
                            if(lst!=null&& lst.Count>0)
                            {
                                state=string.Join(",", lst);
                            }
                            else
                            {
                                state = "";
                            }
                        }

                        break;
                    }
                }
                return state;
            }

            else
                return "";
        }
        public static List<T> DeserializeJsonToList<T>(string json) where T : class
        {
            JsonSerializer serializer = new JsonSerializer();
            StringReader sr = new StringReader(json);
            object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
            List<T> list = o as List<T>;
            return list;
        }
        public void outputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                this.Invoke(new Action(() =>
                {
                    this.textBox2.Text = e.Data;
                    this.label1.Text = $"elapsed:{(DateTime.Now - startTime).TotalSeconds.ToString("f2")}s";
                    try
                    {
                        Stream s = File.Open(System.Windows.Forms.Application.StartupPath + @"\ocr_result.jpg", FileMode.Open);
                        pictureBox1.Image = Bitmap.FromStream(s);
                        s.Close();
                        s.Dispose();
                    }
                    catch
                    {
                    }
                }));
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.InitialDirectory = "c:\\";
                openFileDialog.Filter = "python files (*.exe)|*.exe|All files (*.*)|*.*";
                openFileDialog.RestoreDirectory = true;

                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = openFileDialog.FileName;
                }
            }
        }
    }
}