using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using Ozeki.Media.MediaHandlers;
using Ozeki.Media.MediaHandlers.Video;
using Ozeki.Media.MediaHandlers.Video.CV;
using Ozeki.Media.MediaHandlers.Video.CV.BarcodeData;
using Ozeki.Media.MediaHandlers.Video.CV.Processer;
using DateTime = System.DateTime;
using Ozeki.Media.MediaHandlers.Video.CV.ImageTools;

namespace QRWebCam
{
    public partial class BarcodeForm : Form
    {
        private IBarcodeReader _barcodeReader;
        private WebCamera _webCamera;
        private DrawingImageProvider _imageProvider;
        private MediaConnector _connector;
        private ImageProcesserHandler _imageProcesserHandler;
        private FrameCapture _frameCapture;
        private List<DetectedBarcode> _barcodesList;
        private int _counter;
        private string OutputFileName;
        private string INIFileName;

        public BarcodeForm(string[] args)
        {
            InitializeComponent();

            if (args.Length == 1)
            {
                OutputFileName = args[0];
            }
            else
            {
                try
                {
                    string INIPath = Path.GetDirectoryName(Application.ExecutablePath);
                    INIFileName = INIPath + "\\" + Path.GetFileNameWithoutExtension(Application.ExecutablePath) + ".ini";
                    OutputFileName = File.ReadAllText(@INIFileName);
                }
                catch (Exception)
                {
                }
                
            }

            if (File.Exists(OutputFileName))
            {
                File.Delete(OutputFileName);
            }
            
        }

        void BarcodeForm_Load(object sender, EventArgs e)
        {
            _imageProvider = new DrawingImageProvider();
            _connector = new MediaConnector();
            _imageProcesserHandler = new ImageProcesserHandler();
            _frameCapture = new FrameCapture();
            _barcodeReader = ImageProcesserFactory.CreateBarcodeReader();
            _barcodesList = new List<DetectedBarcode>();
            videoViewer.SetImageProvider(_imageProvider);

            //Включение камеры
            _webCamera = WebCamera.GetDefaultDevice();
            if (_webCamera != null)
            {
                _connector.Connect(_webCamera, _imageProvider);
                videoViewer.SetImageProvider(_imageProvider);

                videoViewer.Start();

                _webCamera.Start();
                statusStrip1.Items[0].Text = @"USB camera started.";
            }
            else
            {
                statusStrip1.Items[0].Text = @"USB camera not found.";
                return;
            }

            //Активизация распознавания
            try
            {
                _barcodeReader.Rotation = false;
                _barcodeReader.Invert = false;
                _barcodeReader.DeeperAnalysis = true;
                _barcodeReader.Monochrome = false;
                _barcodeReader.DetectionOccurred += _barcodeReaderUSBcam_DetectionOccurred;

                _imageProcesserHandler.AddProcesser(_barcodeReader);

                _frameCapture.SetInterval(15);

                _connector.Connect(_webCamera, _frameCapture);
                _connector.Connect(_frameCapture, _imageProcesserHandler);

                _frameCapture.Start();
                                
            }
            catch (Exception ex)
            {
                MessageBox.Show(@"Error occured: " + ex.Message);
            }

        }


        void _barcodeReaderUSBcam_DetectionOccurred(object sender, BarcodeDetectedEventArgs e)
        {
            InvokeGuiThread(() =>
            {
                if (e == null)
                    return;

                //foreach (var barcode in _barcodesList)
                //{
                //    if (e.DetectedBarcode.Equals(barcode))
                //        return;

                //_counter++;

                //_barcodesList.Add(e.DetectedBarcode);

                System.Console.Beep(1000,200);

                //textBoxBarcodes.Text += String.Format("{0}, Date: {1}, Barcode format: {2}, Content: {3}",
                //    _counter, DateTime.Now, e.DetectedBarcode.BarcodeFormat, e.DetectedBarcode.Content) + Environment.NewLine;
                textBoxBarcodes.Text += e.DetectedBarcode.Content + Environment.NewLine;

                try
                {
                    if (OutputFileName!="")
                    {
                        System.IO.File.WriteAllText(@OutputFileName, e.DetectedBarcode.Content);
                        Close();
                    }
                }
                catch (Exception)
                {
                }
                

                
            });
        }

        void buttonStopDetect_Click(object sender, EventArgs e)
        {
            StopDetect();
        }

        void StopDetect()
        {
            _frameCapture.Stop();
            _connector.Disconnect(_frameCapture, _imageProcesserHandler);
            _barcodeReader.DetectionOccurred -= _barcodeReaderUSBcam_DetectionOccurred;
        }

        void buttonClear_Click(object sender, EventArgs e)
        {
            _barcodesList.Clear();
            textBoxBarcodes.Text = String.Empty;
            _counter = 0;
        }

        void InvokeGuiThread(Action action)
        {
            BeginInvoke(action);
        }

              

        private void BarcodeForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Остановить распознавание
            StopDetect();
            
            //Отключить вебкамеру
            _connector.Disconnect(_webCamera, _imageProvider);
            videoViewer.Stop();
            _webCamera.Stop();

        }
    }
}