using Adaptation.Eaf.Management.ConfigurationData.CellAutomation;
using Adaptation.Ifx.Eaf.EquipmentConnector.File.Configuration;
using Adaptation.Shared;
using Adaptation.Shared.Deposition;
using Adaptation.Shared.Methods;
using log4net;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using Tesseract;

namespace Adaptation.FileHandlers.jpeg;

public class ProcessData : IProcessData
{

    private readonly List<object> _Details;

    private readonly ILog _Log;

    public string JobID { get; set; }
    public string MesEntity { get; set; }

    List<object> Shared.Properties.IProcessData.Details => _Details;

    public ProcessData(IFileRead fileRead, Logistics logistics, List<FileInfo> fileInfoCollection)
    {
        if (logistics is null)
        { }
        JobID = logistics.JobID;
        fileInfoCollection.Clear();
        _Details = new List<object>();
        MesEntity = logistics.MesEntity;
        _Log = LogManager.GetLogger(typeof(ProcessData));
        Parse(fileRead);
    }

    private static string Get(string value, bool useSplitForMID)
    {
        string result = value;
        if (useSplitForMID)
        {
            if (result.IndexOf(".") > -1)
                result = result.Split('.')[0].Trim();
            if (result.IndexOf("_") > -1)
                result = result.Split('_')[0].Trim();
            if (result.IndexOf("-") > -1)
                result = result.Split('-')[0].Trim();
        }
        result = string.Concat(result.Substring(0, 1).ToUpper(), result.Substring(1).ToLower());
        return result;
    }

    string IProcessData.GetCurrentReactor(IFileRead fileRead, Logistics logistics, Dictionary<string, string> reactors)
    {
        string result = string.Empty;
        string filePrefixAsMID;
        foreach (KeyValuePair<string, string> keyValuePair in reactors)
        {
            foreach (string filePrefix in keyValuePair.Value.Split('|'))
            {
                filePrefixAsMID = Get(filePrefix, useSplitForMID: true);
                if (logistics.MID.StartsWith(filePrefix) || logistics.MID.StartsWith(filePrefixAsMID))
                {
                    result = keyValuePair.Key;
                    break;
                }
            }
        }
        if (string.IsNullOrEmpty(result) && reactors.Count == 1)
            result = reactors.ElementAt(0).Key;
        return result;
    }

    Tuple<string, Test[], JsonElement[], List<FileInfo>> IProcessData.GetResults(IFileRead fileRead, Logistics logistics, List<FileInfo> fileInfoCollection)
    {
        Tuple<string, Test[], JsonElement[], List<FileInfo>> results;
        List<Test> tests = new();
        foreach (object item in _Details)
            tests.Add(Test.CDE);
        List<IDescription> descriptions = fileRead.GetDescriptions(fileRead, tests, this);
        if (tests.Count != descriptions.Count)
            throw new Exception();
        for (int i = 0; i < tests.Count; i++)
        {
            if (descriptions[i] is not Description description)
                throw new Exception();
            if (description.Test != (int)tests[i])
                throw new Exception();
        }
        List<Description> fileReadDescriptions = (from l in descriptions select (Description)l).ToList();
        string json = JsonSerializer.Serialize(fileReadDescriptions, fileReadDescriptions.GetType());
        JsonElement[] jsonElements = JsonSerializer.Deserialize<JsonElement[]>(json);
        results = new Tuple<string, Test[], JsonElement[], List<FileInfo>>(logistics.Logistics1[0], tests.ToArray(), jsonElements, fileInfoCollection);
        return results;
    }

#pragma warning disable CA1416

    private static byte[] GetBytes(IFileRead fileRead, int endY, int endX, int startY, int startX, int outputQuality)
    {
        byte[] results;
        Point startPoint = new(startX, startY);
        using MemoryStream memoryStream = new();
        EncoderParameters encoderParameters = new(1);
        System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
        ImageCodecInfo imageCodecInfo = (from l in ImageCodecInfo.GetImageEncoders() where l.FormatID == imageFormat.Guid select l).First();
        encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, outputQuality);
        Rectangle rectangle = new(startPoint, new Size(endX - startX, endY - startY));
        using Bitmap bitmap = Image.FromFile(fileRead.ReportFullPath) as Bitmap;
        using Bitmap clonedBitmap = bitmap.Clone(rectangle, bitmap.PixelFormat);
        //clonedBitmap.Save(Path.ChangeExtension(fileRead.ReportFullPath, ".png"), System.Drawing.Imaging.ImageFormat.Png);
        clonedBitmap.Save(memoryStream, imageCodecInfo, encoderParameters);
        results = memoryStream.GetBuffer();
        return results;
    }

#pragma warning restore CA1416

    private static byte[] GetBytes(IFileRead fileRead) => GetBytes(fileRead, 68, 1687, 32, 1094, 95);

    private void Parse(IFileRead fileRead)
    {
        string text;
        using TesseractEngine engine = new(string.Empty, "eng", EngineMode.Default);
        //using Pix img = Pix.LoadFromFile(fileRead.ReportFullPath);
        byte[] bytes = GetBytes(fileRead);
        using Pix img = Pix.LoadFromMemory(bytes);
        using Page page = engine.Process(img);
        text = page.GetText();
        if (string.IsNullOrEmpty(text))
            throw new Exception("OCR Failure!");
        _Details.Add(text);
    }

}