﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TIS.Imaging;
using OpenCvSharp;
using OpenCvSharp.Extensions;
using System.Diagnostics;
using System.Drawing;

namespace TIASshot {
    internal class IScam {
        ICImagingControl _ic;
        Form1 _form;
        Bitmap[] _bmps = new Bitmap[2];
        int _bmpIndex = 0;

        public IScam(Form1 form, ICImagingControl ic) {
            _form = form;
            _ic = ic;

            Config.Load();

        }

        public bool Connect() {
            if (!_ic.LoadShowSaveDeviceState("lastSelectedDeviceState.xml")) {
                return false;
            }
            _ic.Sink = new TIS.Imaging.FrameQueueSink(Retrieve, MediaSubtypes.RGB24, 5);
            _ic.LiveStart();

            return true;
        }

        public void Disconnect() {
            _ic.LiveStop();
        }

        private FrameQueuedResult Retrieve(IFrameQueueBuffer buffer) {
            //var image = buffer.CreateBitmapWrap();
            var frameType = buffer.FrameType;

            using (Mat img = Mat.FromPixelData(frameType.Height, frameType.Width, MatType.CV_8UC3, buffer.GetIntPtr())) {
                using (Mat imgt = img.T()) {
                    _bmps[_bmpIndex] = imgt.ToBitmap();

                    //if (_calibrating > 0) {
                    //    var whitePatch = Cv2.Mean(imgt, _chartMasks[12]);
                    //    Debug.WriteLine($"White patch R {whitePatch.Val2:.00} G {whitePatch.Val1:.00} B {whitePatch.Val0:.00}");
                    //    if (_calibrating % Config.GetInt("CalibrationUpdateInterval") == 0) {
                    //        _snap.GainBlue *= GetRatio((float)whitePatch.Val0, Config.GetFloat("ReferenceB"));
                    //        _snap.GainGrn1 *= GetRatio((float)whitePatch.Val1, Config.GetFloat("ReferenceG"));
                    //        _snap.GainGrn2 = _snap.GainGrn1;
                    //        _snap.GainRed *= GetRatio((float)whitePatch.Val2, Config.GetFloat("ReferenceR"));
                    //        SetCameraParam();
                    //    }
                    //    _calibrating--;
                    //    if (_calibrating == 0) {
                    //        CalcTcc(imgt);
                    //    }
                    //}

                    //if (!_calibrated && _calibrating == 0) {
                    //    DetectChart(imgt);
                    //}
                }
            }
            _form.ShowImage(_bmps[_bmpIndex]);
            _bmpIndex = (_bmpIndex + 1) % 2;
            if (_bmps[_bmpIndex] != null) _bmps[_bmpIndex].Dispose();

            //_form.ShowImage(image);
            return FrameQueuedResult.ReQueue;
        }
    }
}
