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, fileInfoCollection);
    }

    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 (MemoryStream memoryStream, Color[]) Get(IFileRead fileRead, int thresHold, int endY, int endX, int startY, int startX)
    {
        Color color;
        List<Color> colors = new();
        MemoryStream memoryStream = new();
        int middle = (int)(endY - startY * .5);
        Bitmap selectedBitmap = new(endX - startX, endY - startY);
        using Bitmap bitmap = Image.FromFile(fileRead.ReportFullPath) as Bitmap;
        System.Drawing.Imaging.ImageFormat imageFormat = System.Drawing.Imaging.ImageFormat.Png;
        for (int x = startX; x < endX; x++)
        {
            for (int y = startY; y < endY; y++)
            {
                color = bitmap.GetPixel(x, y);
                if (y == middle)
                    colors.Add(color);
                if (color.R > thresHold || color.G > thresHold || color.B > thresHold)
                    selectedBitmap.SetPixel(x - startX, y - startY, Color.Black);
            }
        }
        selectedBitmap.Save(memoryStream, imageFormat);
        return new(memoryStream, colors.ToArray());
    }

    private static void SaveToFile(MemoryStream memoryStream, string extension, string saveFileName)
    {
        System.Drawing.Imaging.ImageFormat imageFormat = extension switch
        {
            ".bmp" => System.Drawing.Imaging.ImageFormat.Bmp,
            ".gif" => System.Drawing.Imaging.ImageFormat.Gif,
            ".jpeg" => System.Drawing.Imaging.ImageFormat.Jpeg,
            ".jpg" => System.Drawing.Imaging.ImageFormat.Jpeg,
            ".png" => System.Drawing.Imaging.ImageFormat.Png,
            ".tiff" => System.Drawing.Imaging.ImageFormat.Tiff,
            _ => throw new Exception("Extension not mapped"),
        };
        using Bitmap bitmap = new(memoryStream);
        bitmap.Save(saveFileName, imageFormat);
    }

#pragma warning restore CA1416

    private static (MemoryStream, Color[]) Get(IFileRead fileRead, int thresHold) => Get(fileRead, thresHold, 68, 1559, 32, 1094);

    private void Parse(IFileRead fileRead, List<FileInfo> fileInfoCollection)
    {
        int thresHold = 76;
        (MemoryStream memoryStream, Color[] colors) = Get(fileRead, thresHold);
        byte[] bytes = memoryStream.GetBuffer();
        using TesseractEngine engine = new(string.Empty, "eng", EngineMode.Default);
        using Pix img = Pix.LoadFromMemory(bytes);
        using Page page = engine.Process(img);
        string text = page.GetText().Trim();
        if (!string.IsNullOrEmpty(text))
            _Log.Debug(text);
        else
        {
            int red = 0;
            int green = 0;
            _Log.Debug("Looking by color");
            string extension = ".png";
            string saveFileName = Path.ChangeExtension(fileRead.ReportFullPath, extension);
            SaveToFile(memoryStream, extension, saveFileName);
            foreach (Color color in colors)
            {
                if (color.R > thresHold)
                    red += 1;
                if (color.G > thresHold)
                    green += 1;
            }
            if (red > green)
                text = "Red*";
            else
                text = "Green*";
            fileInfoCollection.Add(new FileInfo(saveFileName));
        }
        if (memoryStream is not null)
            memoryStream.Dispose();
        _Details.Add(text);
    }

}