using ETC2019.Models.Barcode.Linear;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ETC2019.Controllers
{
    public class BarcodeController
    {
        private string[] AllowExtension { get; set; }
        private string[] Items { get; set; }

        private int x { get; set; }
        private int y { get; set; }
        private int x_2 { get; set; }
        private int y_2 { get; set; }
        private float size_h { get; set; }
        private float size_w { get; set; }

        private BackgroundWorker Worker { get; set; }
        public BarcodeController()
        {
            AllowExtension = new string[] { ".jpg", ".jpeg", ".gif" };

            Worker = new BackgroundWorker() { WorkerReportsProgress = true, WorkerSupportsCancellation = true };

            Worker.DoWork += Worker_DoWork;

            Worker.ProgressChanged += Worker_ProgressChanged;

            Worker.RunWorkerCompleted += Worker_RunWorkerCompleted;
        }

        private void Worker_DoWork(object sender, DoWorkEventArgs e)    //你就當作我沒有寫吧
        {
            for (int i = 0; i < 4; i++)
            {
                Bitmap img = GetImage(i);
                Rectangle_pic(x, y, x_2, y_2, size_w, size_h, img, out string result);
                Console.WriteLine(x);
            }
        }

        private void Worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            throw new NotImplementedException();
        }

        private void Worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {

            
        }

        public int AvailableWidth(int width, ToolStripItemCollection items)
        {
            foreach (ToolStripItem item in items)
            {
                if (item is ToolStripTextBox || item is ToolStripComboBox) { continue; }
                else
                    width = width - item.Size.Width - item.Margin.Left - item.Margin.Right;
            }
            return width;
        }
        
        public  Bitmap GetImage(int index)
        {
            FileStream file = new FileStream(Items[index], FileMode.Open);

            MemoryStream memory = new MemoryStream();

            file.CopyTo(memory);

            file.Close();

            memory.Position = 0;

            return new Bitmap(memory);
        }

        public bool RunWorker()                               //你新寫的
        {
            if (!Worker.IsBusy)
                Worker.RunWorkerAsync(new object[] { x, y, x_2, y_2, Items });
            else
                return false;
            return true;
        }

        public string Click_pic_x(MouseEventArgs e)         //座標X
        {
            

            string x = Convert.ToString(e.X);   

            return x;
        }
        public string Click_pic_y(MouseEventArgs e)         //座標Y
        {
            string y = Convert.ToString(e.Y);
            return y;
        }

        public Image Rectangle_pic(int x , int y , int x_2,int y_2,float size_w, float size_h, Image image, out string result)
        {
            this.x = x;
            this.y = y;
            this.x_2 = x_2;
            this.y_2 = y_2;
            this.size_w = size_w;
            this.size_h = size_h;
            Pen pen = new Pen(Color.Red, 5);
            if (x > x_2)            //確保最左上點是x,變數對調
            {
                int change = x_2;
                x_2 = x;
                x = change;
            }
            if (y > y_2)            //確保最左上點是y,變數對調
            {
                int change = y_2;
                y_2 = y;
                y = change;
            }
                                                        //(1/ size_h)跟(1 / size_w)是還原比例
            int h = (int)((y_2 - y)*(1/ size_h));       //算出"原圖比例的高"數值
            int w = (int)((x_2 - x )* (1 / size_w));    //算出"原圖比例的寬"數值
            y = (int)((y) * (1 / size_h));              //算出"原圖比例的左上角Y"數值
            x = (int)((x) * (1 / size_w));              //算出"原圖比例的左上角X"數值

            Bitmap bmp = new Bitmap(image);
            result = "";

            using (StreamReader sr = new StreamReader(Path.Combine("data", "code39.json")))
            {
                Code39 barcode = JsonConvert.DeserializeObject<Code39>(sr.ReadToEnd());

                result = barcode.Decode(bmp.Clone(new Rectangle(x, y, w, h), bmp.PixelFormat));
            }

            Graphics g = Graphics.FromImage(image);
            g.DrawRectangle(pen, x,  y,   w,  h);
            g.Save();

            return image;
        }



        public bool LoadFolder(string path, out string[] items)
        {
            List<string> itemList = new List<string>(Items = FolderIterator(path, out string[] tempItems) ? tempItems : new string[0]);

            for (int i = 0; i < itemList.Count; i++)
                itemList[i] = Path.GetFileNameWithoutExtension(itemList[i]);

            items = itemList.ToArray();

            return items.Length > 0;
        }

        private bool FolderIterator(string path, out string[] items)
        {
            List<string> itemList = new List<string>();

            foreach (string d in Directory.GetDirectories(path))
                if (FolderIterator(d, out string[] tempItems))
                    itemList.AddRange(tempItems);

            foreach (string f in Directory.GetFiles(path))
                if (AllowExtension.Contains(Path.GetExtension(f)))
                    itemList.Add(f);

            items = itemList.ToArray();

            return items.Length > 0;
        }
    }
}
