using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Text;
using System.Text.Json;

namespace EDAViewer.Singleton.Helper
{

    public partial class Background
    {

        public class EdaDCP
        {

            internal static string GetEdaObjectToHtml(string edaObjectFile, Common common)
            {
                StringBuilder result = new StringBuilder();
                string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
                result.AppendLine("<!DOCTYPE html>");
                result.AppendLine("<html lang=\"en\">");
                result.AppendLine("<head>");
                result.AppendLine("<style>table, th, td{border:1px solid black;} td{padding:2px}</style>");
                result.Append("<title>").Append(title).AppendLine("</title>");
                result.AppendLine("</head>");
                result.AppendLine("<body>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Unit Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Container Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Configuration State").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Configuration Productive State").AppendLine("</th>");
                result.Append("<th nowrap>").Append("LogisticsEquipmentAlias").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
                result.Append("<th nowrap>").Append("StoragePath").AppendLine("</th>");
                result.Append("<th nowrap>").Append("StartTimeFormat").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Filename").AppendLine("</th>");
                result.AppendLine("</tr>");
                result.AppendLine("<tr>");
                result.Append("<td nowrap>").Append(common.UnitName).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.ContainerName).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.ConfigurationState).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.ConfigurationProductiveState).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.LogisticsEquipmentAlias).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.Source).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.StoragePath).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.StartTimeFormat).AppendLine("</td>");
                result.Append("<td nowrap>").Append(common.Filename).AppendLine("</td>");
                result.AppendLine("</tr>");
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Key").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Placeholder").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.LogisticsAttributes)
                {
                    if (item.Length > 2 && !item[2].StartsWith("Z_"))
                    {
                        result.AppendLine("<tr>");
                        foreach (string value in item)
                            result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                        result.AppendLine("</tr>");
                    }
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("ID").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Prefix").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.LogisticsColumns)
                {
                    result.AppendLine("<tr>");
                    foreach (string value in item)
                        result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                    result.AppendLine("</tr>");
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Use").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Order").AppendLine("</th>");
                result.Append("<th nowrap>").Append("FullName").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Alias").AppendLine("</th>");
                result.Append("<th nowrap>").Append("HardWareId").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Description").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Virtual").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Column#").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.Parameters)
                {
                    result.AppendLine("<tr>");
                    foreach (string value in item)
                        result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                    result.AppendLine("</tr>");
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Parent Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.GeneralTriggers)
                {
                    result.AppendLine("<tr>");
                    foreach (string value in item)
                        result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                    result.AppendLine("</tr>");
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
                result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.StartTriggersDCP)
                {
                    result.AppendLine("<tr>");
                    foreach (string value in item)
                        result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                    result.AppendLine("</tr>");
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Fixed").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Scenario").AppendLine("</th>");
                result.Append("<th nowrap>").Append("DefaultJobIndex").AppendLine("</th>");
                result.Append("<th nowrap>").Append("DefaultCarrierIndex").AppendLine("</th>");
                result.Append("<th nowrap>").Append("DefaultSlotIndex").AppendLine("</th>");
                result.Append("<th nowrap>").Append("DataPool").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.LogisticsTriggers)
                {
                    result.AppendLine("<tr>");
                    foreach (string value in item)
                        result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                    result.AppendLine("<td>");
                    result.AppendLine("<table>");
                    result.AppendLine("<tr>");
                    result.Append("<th nowrap>").Append("KeyName").AppendLine("</th>");
                    result.Append("<th nowrap>").Append("ParameterName").AppendLine("</th>");
                    result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
                    result.AppendLine("</tr>");
                    foreach (KeyValuePair<int, string[]> keyValuePair in common.LogisticsTriggersKeysKeyMapping)
                    {
                        result.AppendLine("<tr>");
                        foreach (string value in keyValuePair.Value)
                            result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                        result.AppendLine("</tr>");
                    }
                    result.AppendLine("</table>");
                    result.AppendLine("</td>");
                    result.AppendLine("<td>");
                    result.AppendLine("<table>");
                    result.AppendLine("<tr>");
                    result.Append("<th nowrap>").Append("LogisticsKey").AppendLine("</th>");
                    result.Append("<th nowrap>").Append("Source").AppendLine("</th>");
                    result.Append("<th nowrap>").Append("MappedParameterName").AppendLine("</th>");
                    result.Append("<th nowrap>").Append("Formula").AppendLine("</th>");
                    result.AppendLine("</tr>");
                    foreach (KeyValuePair<int, List<string[]>> keyValuePair in common.LogisticsTriggersCallDefinitionAttributes)
                    {
                        foreach (string[] values in keyValuePair.Value)
                        {
                            if (values.Length > 0 && !values[0].StartsWith("Z_"))
                            {
                                result.AppendLine("<tr>");
                                foreach (string value in values)
                                    result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                                result.AppendLine("</tr>");
                            }
                        }
                    }
                    result.AppendLine("</table>");
                    result.AppendLine("</td>");
                    result.AppendLine("</tr>");
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("<table>");
                result.AppendLine("<tr>");
                result.Append("<th nowrap>").Append("Name").AppendLine("</th>");
                result.Append("<th nowrap>").Append("Rule").AppendLine("</th>");
                result.Append("<th nowrap>").Append("ResolveGlobalVariableBeforeTrigger").AppendLine("</th>");
                result.Append("<th nowrap>").Append("ResetGlobalVariablesAfterTrigger").AppendLine("</th>");
                result.AppendLine("</tr>");
                foreach (string[] item in common.StopTriggersDCP)
                {
                    result.AppendLine("<tr>");
                    foreach (string value in item)
                        result.Append("<td nowrap>").Append(value).AppendLine("</td>");
                    result.AppendLine("</tr>");
                }
                result.AppendLine("</table>");
                result.AppendLine("<hr>");
                result.AppendLine("</body>");
                result.AppendLine("</html>");
                return result.ToString();
            }

            private static string ReplaceNull(object @object)
            {
                if (@object is null)
                    return string.Empty;
                else
                    return @object.ToString();
            }

            private static void TextResolveEntry(StringBuilder result, dynamic expandoObject, int level, string super, int? i, bool group)
            {
                level += 1;
                foreach (dynamic entry in expandoObject)
                {
                    if (entry.Value is ExpandoObject)
                        TextResolveEntry(result, entry.Value, level, string.Concat(super, " : ", entry.Key), i, group);
                    else
                    {
                        if (!(entry.Value is ICollection<object>))
                        {
                            if (i is null)
                                result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("--->").AppendLine(ReplaceNull(entry.Value));
                            else
                                result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value));
                        }
                        else
                        {
                            if (!group)
                            {
                                for (i = 0; i.Value < entry.Value.Count; i++)
                                {
                                    if (entry.Value[i.Value] is ExpandoObject)
                                        TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
                                    else
                                        result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
                                }
                            }
                            else
                            {
                                for (i = 0; i.Value < entry.Value.Count; i++)
                                {
                                    if (!(entry.Value[i.Value] is ExpandoObject))
                                        result.Append(level).Append(") ").Append(super).Append(" : ").Append(entry.Key).Append("[").Append(i.Value).Append("]--->").AppendLine(ReplaceNull(entry.Value[i.Value]));
                                }
                                for (i = 0; i.Value < entry.Value.Count; i++)
                                {
                                    if (entry.Value[i.Value] is ExpandoObject)
                                        TextResolveEntry(result, entry.Value[i.Value], level, string.Concat(super, " : ", entry.Key), i.Value, group);
                                }
                            }
                            i = null;
                        }
                    }
                }
                level -= 1;
            }

            internal static string GetText(string edaObjectFile, Common common, string json)
            {
                StringBuilder result = new StringBuilder();
                if (result.Length > 0) //Skipping because System.Text.Json changed the way Expando works 
                {
                    string title = string.Concat(Path.GetFileName(edaObjectFile), " - ", common.Source);
                    dynamic expandoObject = JsonSerializer.Deserialize<ExpandoObject>(json);
                    result.AppendLine(title);
                    result.AppendLine("Loop -> \"Normal\"");
                    result.AppendLine(edaObjectFile);
                    result.AppendLine();
                    TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: false);
                    result.AppendLine();
                    result.AppendLine();
                    result.AppendLine();
                    result.AppendLine(title);
                    result.AppendLine("Loop -> \"Grouped\"");
                    result.AppendLine(edaObjectFile);
                    result.AppendLine();
                    TextResolveEntry(result, expandoObject, 0, string.Empty, null, group: true);
                }
                return result.ToString();
            }

            internal static string GetEdaObjectToDMSGridFormat(string edaObjectFile, Common common, bool useAlias)
            {
                StringBuilder result = new StringBuilder();
                string[] segments;
                int? recordStart = null;
                string name = string.Concat(common.LogisticsEquipmentAlias, "_", common.ContainerName);
                result.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>");
                result.Append("<Format Name=\"").Append(name).Append("\">").AppendLine();
                result.AppendLine("  <General RecordStart=\"\" RecordLength=\"0\" ReadCommand=\"\" DecimalSeparator=\".\">");
                result.AppendLine("    <RecordTerminator>&lt;13&gt;&lt;10&gt;</RecordTerminator>");
                result.AppendLine("    <ColumnSeparator>&lt;9&gt;</ColumnSeparator>");
                result.AppendLine("  </General>");
                result.AppendLine("  <Fields>");
                for (int i = 0; i < common.Parameters.Count; i++)
                {
                    if (recordStart is null && common.Parameters[i][3] == "RECORD_START")
                        recordStart = i;
                    if (recordStart.HasValue && common.Parameters[i][0] == "True")
                    {
                        if (useAlias && !string.IsNullOrEmpty(common.Parameters[i][3]))
                            name = common.Parameters[i][3].Replace("'", string.Empty);
                        else
                        {
                            segments = common.Parameters[i][2].Split('/');
                            name = segments[segments.Length - 1];
                        }
                        result.Append("    <Field Name=\"").Append(name).Append("\" ColumnNumber=\"").Append(i + common.LogisticsColumns.Count + 2).Append("\" StartPosition=\"\" Length=\"\" DataType=\"Text\" NullReplacement=\"\" />").AppendLine();
                    }
                }
                result.AppendLine("  </Fields>");
                result.AppendLine("  <Conditions>");
                result.AppendLine("    <Column />");
                result.AppendLine("    <Row>");
                result.AppendLine("      <Condition>");
                result.AppendLine("        <SkipHeaderCount>7</SkipHeaderCount>");
                result.AppendLine("        <SkipRowFilter>0</SkipRowFilter>");
                result.AppendLine("        <SkipRowValue>");
                result.AppendLine("        </SkipRowValue>");
                result.AppendLine("      </Condition>");
                result.AppendLine("    </Row>");
                result.AppendLine("  </Conditions>");
                result.AppendLine("</Format>");
                return result.ToString();
            }

            internal static string GetEdaObjectToAPCParameter(string edaObjectFile, Common common)
            {
                StringBuilder result = new StringBuilder();
                string parameter;
                string[] segments;
                string parameterSub35;
                string name = string.Concat(common.LogisticsEquipmentAlias, "_", common.ContainerName);
                result.AppendLine("ExportFileVersion=1.0.6");
                result.AppendLine("ExportFromTabsheet=Para");
                result.AppendLine("FieldName\tLongName\tMatchMode\tEquipment\tName\tPdsfNameConvCol\tPdsfNameDataType\tType\tChamberInfo\tUnifiedPara\tDateFormat\tUsername\tId\tWorkcenterId\tSite\tArea\tWorkcenter\tValidFrom\tValidTo");
                result.AppendLine("TIME_PREV_DIFF\tTIME_PREV_DIFF\tEXACT\t*\tTIME_PREV_DIFF\t\tNUMERIC\tRUN\t\tTIME_PREV_DIFF\t\tPHARES\t95069\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
                result.AppendLine("TIME\tTIME\tEXACT\t*\tTIME\t\tNUMERIC\tRUN\t\tTIME\t\tPHARES\t95070\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
                for (int i = 0; i < common.Parameters.Count; i++)
                {
                    if (common.Parameters[i][0] == "True")
                    {
                        segments = common.Parameters[i][2].Split('/');
                        parameter = segments[segments.Length - 1];
                        if (parameter.Length < 35)
                            parameterSub35 = parameter;
                        else
                            parameterSub35 = parameter.Substring(0, 35);
                        result.Append(parameterSub35).Append("\tDIVERSE\tEXACT\t*\t").Append(parameterSub35).AppendLine("\t\tNUMERIC\tRUN\t\t\t\tPHARES\t9000000012\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
                    }
                }
                result.AppendLine();
                result.AppendLine();
                result.AppendLine();
                for (int i = 0; i < common.Parameters.Count; i++)
                {
                    if (common.Parameters[i][0] == "True")
                    {
                        segments = common.Parameters[i][2].Split('/');
                        parameter = segments[segments.Length - 1];
                        result.Append(parameter).Append("\tDIVERSE\tEXACT\t*\t").Append(parameter).AppendLine("\t\tNUMERIC\tRUN\t\t\t\tPHARES\t9000000012\t4571\tMesa\t\t\t4/15/2020 6:10 PM");
                    }
                }
                return result.ToString();
            }

            internal static string GetEdaObjectToAPCRunKeyNumber(string edaObjectFile, Common common)
            {
                StringBuilder result = new StringBuilder();
                string parameter;
                string[] segments;
                string parameterSub21;
                string parameterSub35;
                string name = string.Concat(common.LogisticsEquipmentAlias, "_", common.ContainerName);
                result.AppendLine("ExportFileVersion=1.0.6");
                result.AppendLine("ExportFromTabsheet=Run-Keynumbers");
                result.AppendLine("FeatureName\tShortName\tChamber\tComments\tVarMode\tPara\tExclude0\tTrigOn1\tTrigOn2\tTrigOn3\tTrigOff1\tTrigOff2\tTrigOff3\tTrigDelay\tTrigNorm\tTrigNvl\tTrigTrg\tAddCondOn\tActive\tFilter1\tFilter2\tFilter3\tFilter4\tUnit\tId\tWorkcenterId\tSite\tArea\tWorkcenter\tUsername\tValidFrom\tValidTo");
                for (int i = 0; i < common.Parameters.Count; i++)
                {
                    if (common.Parameters[i][0] == "True")
                    {
                        segments = common.Parameters[i][2].Split('/');
                        parameter = segments[segments.Length - 1];
                        if (parameter.Length < 35)
                            parameterSub35 = parameter;
                        else
                            parameterSub35 = parameter.Substring(0, 35);
                        if (parameter.Length < 21)
                            parameterSub21 = parameter;
                        else
                            parameterSub21 = parameter.Substring(0, 21);
                        result.Append(parameterSub21).Append("_MIN\t").Append(parameterSub21).Append("_MIN\t\t\tMIN\t").Append(parameterSub35).AppendLine("\t0\tTIME\t=\tRUNSTART\tTIME\t=\tRUNEND\t\t\t\t\t\t1\t\t\t\t\t\t-1\t-1\t\t\t\tECPHARES\t5/2/2017 2:44 PM");
                    }
                }
                result.AppendLine();
                result.AppendLine();
                result.AppendLine();
                for (int i = 0; i < common.Parameters.Count; i++)
                {
                    if (common.Parameters[i][0] == "True")
                    {
                        segments = common.Parameters[i][2].Split('/');
                        parameter = segments[segments.Length - 1];
                        result.Append(parameter).Append("_MIN\t").Append(parameter).Append("_MIN\t\t\tMIN\t").Append(parameter).AppendLine("\t0\tTIME\t=\tRUNSTART\tTIME\t=\tRUNEND\t\t\t\t\t\t1\t\t\t\t\t\t-1\t-1\t\t\t\tECPHARES\t5/2/2017 2:44 PM");
                    }
                }
                return result.ToString();
            }

        }

    }

}