using Newtonsoft.Json;
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;

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

        private void Form1_Load(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "*.PNG|*.PNG";
            openFileDialog.Multiselect = false;
            openFileDialog.ShowDialog();

            if (File.Exists(openFileDialog.FileName))
            {
                var srcfile = openFileDialog.FileName;
                string resultfile = Path.GetDirectoryName(srcfile) + "\\" + Path.GetFileNameWithoutExtension(srcfile) + "_Mark.png";
                callcounter(srcfile, resultfile);
            }
        }
        Result callcounter(string srcfile, string resultfile) {
            var p = new Process();
            p.StartInfo = new ProcessStartInfo(Application.StartupPath + "\\wafer_die_counter\\wafer_die_counter.exe");
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;            
            p.StartInfo.Arguments = $"\"{srcfile}\" \"{resultfile}\"";
            p.Start();
            p.WaitForExit(45 * 1000);//最长等待45秒
            var x = p.StandardOutput.ReadToEndAsync();
            if (x.Wait(1000))
                return JsonConvert.DeserializeObject<Result>(x.Result);
            else
            {
                p.Kill();
                return new Result() { msg = "外部点料算法调用失败" };
            }
        }
    }

    [Serializable]
    public class Result
    {
        public bool success = false;
        public int qty = 0;
        public string msg = "";//错误消息
    }
}