using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using AR;

namespace Project
{
    public partial class FMain
    {

        Tuple<int, List<string>> BarcodeRegExProcess(
            List<Class.RegexPattern> patterns,
            List<Class.RegexPattern> patternsEx,
            Class.VisionData vdata, string barcodeSymbol,
            string bcd, out bool IgnoreBarcode, out bool findregex)
        {
            //var patterns = PUB.Result.BCDPattern;
            IgnoreBarcode = false;
            findregex = false;

            //get : same symbol data
            List<Class.RegexPattern> pats;
            if (patterns != null)
            {
                if (barcodeSymbol.isEmpty() == false) pats = patterns.Where(t => t.IsEnable == true && (string.IsNullOrEmpty(t.Symbol) || t.Symbol == barcodeSymbol)).OrderBy(t => t.Seq).ToList();
                else pats = patterns.Where(t => t.IsEnable == true).OrderBy(t => t.Seq).ToList();
            }
            else pats = new List<Class.RegexPattern>();


            List<Class.RegexPattern> patsEx;
            if (patternsEx == null) patsEx = new List<Class.RegexPattern>();
            else
            {
                if (barcodeSymbol.isEmpty() == false) patsEx = patternsEx.Where(t => string.IsNullOrEmpty(t.Symbol) || t.Symbol == barcodeSymbol).OrderBy(t => t.Seq).ToList();
                else patsEx = patternsEx.Where(t => t.IsEnable == true).OrderBy(t => t.Seq).ToList();
            }



            //모델정보의  허용  심볼인지  확인한다  221017
            var vm = PUB.Result.vModel;
            if (vm != null)
            {
                if (vm.BCD_DM == false && barcodeSymbol == "2")
                {
                    PUB.log.AddAT($"Inactive in model(DM):{bcd}");
                    IgnoreBarcode = true;
                    return new Tuple<int, List<string>>(0, new List<string>());
                }
                else if (vm.BCD_1D == false && (barcodeSymbol == "6" || barcodeSymbol == "11"))
                {
                    PUB.log.AddAT($"Inactive in model(1D):{bcd}");
                    IgnoreBarcode = true;
                    return new Tuple<int, List<string>>(0, new List<string>());
                }
                else if (vm.BCD_QR == false && (barcodeSymbol == "1"))
                {
                    PUB.log.AddAT($"Inactive in model(QR):{bcd}");
                    IgnoreBarcode = true;
                    return new Tuple<int, List<string>>(0, new List<string>());
                }
            }

            //check barcode pattern
            if (pats.Any() == false)
            {
                PUB.log.AddAT($"No registered pattern(SYM={barcodeSymbol}) Model:{vm.Title}");
                return new Tuple<int, List<string>>(0, new List<string>());
            }

            //이 바코드가 무시바코드에 있는지 먼저 검사한다 220718
            foreach (var pt in patsEx)
            {
                //skip disable item
                if (pt.IsEnable == false) continue;

                //check regex
                var regx = new Regex(pt.Pattern, RegexOptions.IgnoreCase, new TimeSpan(0, 0, 10));
                if (regx.IsMatch(bcd))
                {
                    PUB.log.AddAT($"Ignore barcode:{bcd},PAT:{pt.Pattern},SYM:{pt.Symbol}");
                    IgnoreBarcode = true;
                    break;
                }
            }
            if (IgnoreBarcode)
            {
                return new Tuple<int, List<string>>(0, new List<string>());
            }


            //동작중에 들어오는 바코드의 자동처리코드 추가 250926
            if (PUB.sm.Step == eSMStep.RUN || PUB.sm.Step == eSMStep.PAUSE || PUB.sm.Step == eSMStep.WAITSTART)
            {

                var OPT_PrinterOff = VAR.BOOL[eVarBool.Opt_DisablePrinter];
                var OPT_CameraOff = PUB.OPT_CAMERA();
                var OPT_BYPASS = PUB.OPT_BYPASS();

                if (OPT_BYPASS == false)
                {
                    //기본 벤더이름
                    if (PUB.Result.vModel.Def_Vname.isEmpty() == false)
                    {
                        if (vdata.VNAME.Equals(PUB.Result.vModel.Def_Vname) == false)
                        {
                            vdata.VNAME = PUB.Result.vModel.Def_Vname;
                            vdata.VNAME_Trust = true;
                            PUB.log.Add($"Defaul V.Name Set to {PUB.Result.vModel.Def_Vname}");
                        }
                    }

                    //기본 MFG
                    if (PUB.Result.vModel.Def_MFG.isEmpty() == false)
                    {
                        if (vdata.MFGDATE.Equals(PUB.Result.vModel.Def_MFG) == false)
                        {
                            vdata.MFGDATE = PUB.Result.vModel.Def_MFG;
                            vdata.MFGDATE_Trust = true;
                            PUB.log.Add($"Defaul MFGDATE Set to {PUB.Result.vModel.Def_MFG}");
                        }
                    }

                    //파트넘버무시
                    if (PUB.Result.vModel.IgnorePartNo)
                    {
                        vdata.PARTNO_Trust = true;
                    }

                    //배치무시
                    if (PUB.Result.vModel.IgnoreBatch)
                    {

                    }

                    //프린트를 하지 않는 경우에는 프린트 위치를 자동으로 처리한다.
                    if (OPT_PrinterOff == true)
                    {
                        vdata.PrintPositionData = "0";
                        vdata.PrintPositionCheck = true;
                    }
                }
                else
                {
                    if (vdata.VNAME_Trust == false)
                    {
                        vdata.VNAME = "BYPASS";
                        vdata.VNAME_Trust = true;
                    }
                }
            }

            var ValueApplyCount = 0;
            ValueApplyCount = 0;
            List<string> list = new List<string>();
            findregex = false;
            foreach (var pt in pats)
            {
                //skip disable item
                if (pt.IsEnable == false) continue;

                var regx = new Regex(pt.Pattern, RegexOptions.IgnoreCase, new TimeSpan(0, 0, 10));
                if (regx.IsMatch(bcd))
                {
                    findregex = true;
                    //find data
                    var matchs = regx.Matches(bcd);
                    foreach (System.Text.RegularExpressions.Match mat in matchs)
                    {

                        if (vdata == null) ValueApplyCount += 1;
                        else
                        {
                            foreach (var matchdata in pt.Groups)
                            {
                                if (matchdata.GroupNo <= mat.Groups.Count)
                                {
                                    var data = mat.Groups[matchdata.GroupNo];
                                    if (PUB.SetBCDValue(vdata, matchdata.TargetPos, data.Value, pt.IsTrust))
                                        ValueApplyCount += 1;
                                }
                            }
                        }
                    }

                    if (vdata != null && pt.IsAmkStd)// && bcdObj.barcodeSymbol == "1")
                    {
                        vdata.QRInputRaw = bcd;
                    }

                    if (vdata != null)
                        PUB.log.AddI($"[{pt.Description}]=>{bcd}");

                    list.Add(pt.Customer + "|" + pt.Description);
                }
                else
                {
                    //PUB.log.AddAT($"(X)Match ({pt.Pattern}) Data={bcd}");
                }
            }
            return new Tuple<int, List<string>>(ValueApplyCount, list);
        }

        /// <summary>
        /// barcod eprocess
        /// </summary>
        void BarcodeProcess()
        {
            //coffee
            //get regexpress patterns
            var patterns = PUB.Result.BCDPattern;
            var itemC = PUB.Result.ItemDataC;
            var vdata = itemC.VisionData;
            bool vQtyOK = false;

            //No Run - Confirm Data
            if (vdata.Confirm) return;
            var vm = PUB.Result.vModel;

            lock (vdata.barcodelist)
            {
                foreach (var item in vdata.barcodelist)
                {
                    //var src = item.Value.barcodeSource;
                    var bcd = item.Value.Data;
                    var bcdObj = item.Value;

                    //already checked
                    if (bcdObj.RegExConfirm) continue;

                    var ValueApplyCount = BarcodeRegExProcess(PUB.Result.BCDPattern, PUB.Result.BCDIgnorePattern, vdata, bcdObj.barcodeSymbol, bcd, out bool IgnoreBcd, out bool findregex);
                    bcdObj.Ignore = IgnoreBcd;

                    //기타바코드 무시기능 적용 221018
                    if (vm != null && vm.IgnoreOtherBarcode == true && findregex == false)
                        bcdObj.Ignore = true;

                    bcdObj.RefExApply = (ValueApplyCount?.Item1 ?? 0) > 0;
                    bcdObj.RegExConfirm = true;
                }
            }

            //all process sequence
            if (BCDProcess_ALL(itemC, "SPS", PUB.sm.Step == eSMStep.RUN) != EResultKeyence.Nothing)
            {
                //nothing : multisid condition
            }


        }
    }
}