using System.Text;

namespace Inspectron.Epson.SOAP
{
    public class SoapEpsonPrint
    {
        private StringBuilder message = new StringBuilder();
        private int halftone = 0;
        private double brightness = 1.0;
        private bool force = false;

        // Font constants
        public const string FONT_A = "font_a";
        public const string FONT_B = "font_b";
        public const string FONT_C = "font_c";
        public const string FONT_D = "font_d";
        public const string FONT_E = "font_e";
        public const string FONT_SPECIAL_A = "special_a";
        public const string FONT_SPECIAL_B = "special_b";

        // Alignment constants
        public const string ALIGN_LEFT = "left";
        public const string ALIGN_CENTER = "center";
        public const string ALIGN_RIGHT = "right";

        // Color constants
        public const string COLOR_NONE = "none";
        public const string COLOR_1 = "color_1";
        public const string COLOR_2 = "color_2";
        public const string COLOR_3 = "color_3";
        public const string COLOR_4 = "color_4";

        // Feed constants
        public const string FEED_PEELING = "peeling";
        public const string FEED_CUTTING = "cutting";
        public const string FEED_CURRENT_TOF = "current_tof";
        public const string FEED_NEXT_TOF = "next_tof";

        // Mode constants
        public const string MODE_MONO = "mono";
        public const string MODE_GRAY16 = "gray16";

        // Barcode constants
        public const string BARCODE_UPC_A = "upc_a";
        public const string BARCODE_UPC_E = "upc_e";
        public const string BARCODE_EAN13 = "ean13";
        public const string BARCODE_JAN13 = "jan13";
        public const string BARCODE_EAN8 = "ean8";
        public const string BARCODE_JAN8 = "jan8";
        public const string BARCODE_CODE39 = "code39";
        public const string BARCODE_ITF = "itf";
        public const string BARCODE_CODABAR = "codabar";
        public const string BARCODE_CODE93 = "code93";
        public const string BARCODE_CODE128 = "code128";
        public const string BARCODE_GS1_128 = "gs1_128";
        public const string BARCODE_GS1_DATABAR_OMNIDIRECTIONAL = "gs1_databar_omnidirectional";
        public const string BARCODE_GS1_DATABAR_TRUNCATED = "gs1_databar_truncated";
        public const string BARCODE_GS1_DATABAR_LIMITED = "gs1_databar_limited";
        public const string BARCODE_GS1_DATABAR_EXPANDED = "gs1_databar_expanded";
        public const string BARCODE_CODE128_AUTO = "code128_auto";

        // HRI constants
        public const string HRI_NONE = "none";
        public const string HRI_ABOVE = "above";
        public const string HRI_BELOW = "below";
        public const string HRI_BOTH = "both";

        // Level constants
        public const string LEVEL_0 = "level_0";
        public const string LEVEL_1 = "level_1";
        public const string LEVEL_2 = "level_2";
        public const string LEVEL_3 = "level_3";
        public const string LEVEL_4 = "level_4";
        public const string LEVEL_5 = "level_5";
        public const string LEVEL_6 = "level_6";
        public const string LEVEL_7 = "level_7";
        public const string LEVEL_8 = "level_8";
        public const string LEVEL_L = "level_l";
        public const string LEVEL_M = "level_m";
        public const string LEVEL_Q = "level_q";
        public const string LEVEL_H = "level_h";
        public const string LEVEL_DEFAULT = "default";

        // Line constants
        public const string LINE_THIN = "thin";
        public const string LINE_MEDIUM = "medium";
        public const string LINE_THICK = "thick";
        public const string LINE_THIN_DOUBLE = "thin_double";
        public const string LINE_MEDIUM_DOUBLE = "medium_double";
        public const string LINE_THICK_DOUBLE = "thick_double";

        // Direction constants
        public const string DIRECTION_LEFT_TO_RIGHT = "left_to_right";
        public const string DIRECTION_BOTTOM_TO_TOP = "bottom_to_top";
        public const string DIRECTION_RIGHT_TO_LEFT = "right_to_left";
        public const string DIRECTION_TOP_TO_BOTTOM = "top_to_bottom";

        // Cut constants
        public const string CUT_NO_FEED = "no_feed";
        public const string CUT_FEED = "feed";
        public const string CUT_RESERVE = "reserve";
        public const string FULL_CUT_NO_FEED = "no_feed_fullcut";
        public const string FULL_CUT_FEED = "feed_fullcut";
        public const string FULL_CUT_RESERVE = "reserve_fullcut";

        // Drawer constants
        public const string DRAWER_1 = "drawer_1";
        public const string DRAWER_2 = "drawer_2";

        // Pulse constants
        public const string PULSE_100 = "pulse_100";
        public const string PULSE_200 = "pulse_200";
        public const string PULSE_300 = "pulse_300";
        public const string PULSE_400 = "pulse_400";
        public const string PULSE_500 = "pulse_500";

        // Pattern constants
        public const string PATTERN_NONE = "none";
        public const string PATTERN_0 = "pattern_0";
        public const string PATTERN_1 = "pattern_1";
        public const string PATTERN_2 = "pattern_2";
        public const string PATTERN_3 = "pattern_3";
        public const string PATTERN_4 = "pattern_4";
        public const string PATTERN_5 = "pattern_5";
        public const string PATTERN_6 = "pattern_6";
        public const string PATTERN_7 = "pattern_7";
        public const string PATTERN_8 = "pattern_8";
        public const string PATTERN_9 = "pattern_9";
        public const string PATTERN_10 = "pattern_10";
        public const string PATTERN_A = "pattern_a";
        public const string PATTERN_B = "pattern_b";
        public const string PATTERN_C = "pattern_c";
        public const string PATTERN_D = "pattern_d";
        public const string PATTERN_E = "pattern_e";
        public const string PATTERN_ERROR = "error";
        public const string PATTERN_PAPER_END = "paper_end";

        // Layout constants
        public const string LAYOUT_RECEIPT = "receipt";
        public const string LAYOUT_RECEIPT_BM = "receipt_bm";
        public const string LAYOUT_LABEL = "label";
        public const string LAYOUT_LABEL_BM = "label_bm";

        // Halftone constants
        public const int HALFTONE_DITHER = 0;
        public const int HALFTONE_ERROR_DIFFUSION = 1;
        public const int HALFTONE_THRESHOLD = 2;

        public SoapEpsonPrint AddText(string data)
        {
            AddRow("text", Utils.EscapeMarkup(data));
            return this;
        }

        public SoapEpsonPrint AddTextLang(string lang)
        {
            message.Append($"<text lang=\"{lang}\"/>");
            return this;
        }

        public SoapEpsonPrint AddTextAlign(string align)
        {
            AddRow("text", null, new Dictionary<string, object> { { "align", align } });
            return this;
        }

        public SoapEpsonPrint AddTextRotate(string rotate)
        {
            var s = Utils.GetBoolAttr("rotate", rotate);
            message.Append($"<text{s}/>");
            return this;
        }

        public SoapEpsonPrint AddTextLineSpace(string linespc)
        {
            AddRow("text", null, new Dictionary<string, object> { { "linespc", linespc } });
            return this;
        }

        public SoapEpsonPrint AddTextFont(string font)
        {
            AddRow("text", null, new Dictionary<string, object> { { "font", font } });
            return this;
        }

        public SoapEpsonPrint AddTextSmooth(string smooth)
        {
            var s = Utils.GetBoolAttr("smooth", smooth);
            message.Append($"<text{s}/>");
            return this;
        }

        public SoapEpsonPrint AddTextDouble(string dw, string dh)
        {
            var s = new StringBuilder();
            if (dw != null)
            {
                s.Append(Utils.GetBoolAttr("dw", dw));
            }
            if (dh != null)
            {
                s.Append(Utils.GetBoolAttr("dh", dh));
            }
            message.Append($"<text{s}/>");
            return this;
        }

        public SoapEpsonPrint AddTextSize(int width, int height)
        {
            AddRow("text", null, new Dictionary<string, object>
            {
                { "width", width },
                { "height", height }
            });
            return this;
        }

        public SoapEpsonPrint AddTextStyle(bool reverse, bool ul, bool em, string color)
        {
            AddRow("text", null, new Dictionary<string, object>
            {
                { "reverse", reverse },
                { "ul", ul },
                { "em", em },
                { "color", color }
            });
            return this;
        }

        public SoapEpsonPrint AddTextPosition(int x)
        {
            AddRow("text", null, new Dictionary<string, object> { { "x", x } });
            return this;
        }

        public SoapEpsonPrint AddTextVPosition(int y)
        {
            AddRow("text", null, new Dictionary<string, object> { { "y", y } });
            return this;
        }

        public SoapEpsonPrint AddSymbol(string data, Symbol type, SymbolOptions options = null)
        {
            var attrs = new Dictionary<string, object>
            {
                { "type", GetSymbolTypeString(type) }
            };

            if (options != null)
            {
                if (options.ErrorCorrectionLevel.HasValue)
                    attrs["level"] = options.ErrorCorrectionLevel.Value;
                if (options.Width.HasValue)
                    attrs["width"] = options.Width.Value;
                if (options.Height.HasValue)
                    attrs["height"] = options.Height.Value;
                if (options.Size.HasValue)
                    attrs["size"] = options.Size.Value;
            }

            AddRow("symbol", Utils.EscapeControl(Utils.EscapeMarkup(data)), attrs);
            return this;
        }

        public SoapEpsonPrint AddQRCode(string data, QRCodeOptions options = null)
        {
            var attrs = new Dictionary<string, object>
            {
                { "type", GetSymbolTypeString(Symbol.QRCODE_MODEL_2) }
            };

            if (options != null)
            {
                if (options.ErrorCorrectionLevel.HasValue)
                    attrs["level"] = options.ErrorCorrectionLevel.Value;
                if (options.Size.HasValue)
                    attrs["width"] = options.Size.Value;
            }

            AddRow("symbol", Utils.EscapeMarkup(data), attrs);
            return this;
        }

        public SoapEpsonPrint AddFeedUnit(string unit)
        {
            message.Append($"<feed unit=\"{unit}\"/>");
            return this;
        }

        public SoapEpsonPrint AddFeedLine(int line)
        {
            AddRow("feed", null, new Dictionary<string, object> { { "line", line } });
            return this;
        }

        public SoapEpsonPrint AddFeed()
        {
            message.Append("<feed/>");
            return this;
        }

        public SoapEpsonPrint AddFeedPosition(string pos)
        {
            AddRow("feed", null, new Dictionary<string, object> { { "pos", pos } });
            return this;
        }

        public SoapEpsonPrint AddImage(string base64ImageData, string width, string height)
        {
            AddRow("image", base64ImageData, new Dictionary<string, object>
            {
                { "height", height },
                { "width", width },
                { "color", "color_1" },
                { "mode", "mono" }
            });
            return this;
        }

        public SoapEpsonPrint AddLogo(string key1, string key2)
        {
            AddRow("logo", null, new Dictionary<string, object>
            {
                { "key1", key1 },
                { "key2", key2 }
            });
            return this;
        }

        public SoapEpsonPrint AddBarcode(string data, string type, int hri, string font, int width, int height)
        {
            AddRow("barcode", Utils.EscapeControl(Utils.EscapeMarkup(data)), new Dictionary<string, object>
            {
                { "type", type },
                { "hri", hri },
                { "font", font },
                { "width", width },
                { "height", height }
            });
            return this;
        }

        public SoapEpsonPrint AddHLine(int x1, int x2, string style)
        {
            AddRow("hline", null, new Dictionary<string, object>
            {
                { "x1", x1 },
                { "x2", x2 },
                { "style", style }
            });
            return this;
        }

        public SoapEpsonPrint AddVLineBegin(int x, string style)
        {
            AddRow("vline", null, new Dictionary<string, object>
            {
                { "x", x },
                { "style", style }
            });
            return this;
        }

        public SoapEpsonPrint AddVLineEnd(int x, string style)
        {
            AddRow("vline", null, new Dictionary<string, object>
            {
                { "x", x },
                { "style", style }
            });
            return this;
        }

        public SoapEpsonPrint AddRotateBegin()
        {
            message.Append("<rotate-begin/>");
            return this;
        }

        public SoapEpsonPrint AddRotateEnd()
        {
            message.Append("<rotate-end/>");
            return this;
        }

        public SoapEpsonPrint AddCut(string type)
        {
            AddRow("cut", null, new Dictionary<string, object> { { "type", type } });
            return this;
        }

        public SoapEpsonPrint AddSound(object pattern, object repeat, string cycle)
        {
            AddRow("sound", null, new Dictionary<string, object>
            {
                { "pattern", pattern },
                { "repeat", repeat },
                { "cycle", cycle }
            });
            return this;
        }

        public SoapEpsonPrint AddRecovery()
        {
            AddRow("recovery");
            return this;
        }

        public SoapEpsonPrint AddReset()
        {
            AddRow("reset");
            return this;
        }

        public SoapEpsonPrint AddCommand(string data)
        {
            message.Append($"<command>{Utils.ToHexBinary(data)}</command>");
            return this;
        }

        public SoapEpsonPrint KickOutDrawer(string drawer = DRAWER_1, string pulse = PULSE_100)
        {
            AddRow("pulse", null, new Dictionary<string, object>
            {
                { "drawer", drawer },
                { "time", pulse }
            });
            return this;
        }

        public override string ToString()
        {
            var s = force ? " force=\"true\"" : "";
            return $"<epos-print xmlns=\"http://www.epson-pos.com/schemas/2011/03/epos-print\"{s}>{message}</epos-print>";
        }

        public void AddRow(string field, string value = null, Dictionary<string, object> fields = null)
        {
            message.Append($"<{field}");

            if (fields != null)
            {
                foreach (var kvp in fields)
                {
                    if (kvp.Value == null)
                        continue;

                    message.Append($" {kvp.Key}=\"{kvp.Value}\"");
                }
            }

            if (string.IsNullOrEmpty(value))
            {
                message.Append("/>");
            }
            else
            {
                message.Append($">{value}</{field}>");
            }
        }

        private string GetSymbolTypeString(Symbol symbol)
        {
            return symbol switch
            {
                Symbol.PDF417_STANDARD => "pdf417_standard",
                Symbol.PDF417_TRUNCATED => "pdf417_truncated",
                Symbol.QRCODE_MODEL_1 => "qrcode_model_1",
                Symbol.QRCODE_MODEL_2 => "qrcode_model_2",
                Symbol.QRCODE_MICRO => "qrcode_micro",
                Symbol.MAXICODE_MODE_2 => "maxicode_mode_2",
                Symbol.MAXICODE_MODE_3 => "maxicode_mode_3",
                Symbol.MAXICODE_MODE_4 => "maxicode_mode_4",
                Symbol.MAXICODE_MODE_5 => "maxicode_mode_5",
                Symbol.MAXICODE_MODE_6 => "maxicode_mode_6",
                Symbol.GS1_DATABAR_STACKED => "gs1_databar_stacked",
                Symbol.GS1_DATABAR_STACKED_OMNIDIRECTIONAL => "gs1_databar_stacked_omnidirectional",
                Symbol.GS1_DATABAR_EXPANDED_STACKED => "gs1_databar_expanded_stacked",
                Symbol.AZTECCODE_FULLRANGE => "azteccode_fullrange",
                Symbol.AZTECCODE_COMPACT => "azteccode_compact",
                Symbol.DATAMATRIX_SQUARE => "datamatrix_square",
                Symbol.DATAMATRIX_RECTANGLE_8 => "datamatrix_rectangle_8",
                Symbol.DATAMATRIX_RECTANGLE_12 => "datamatrix_rectangle_12",
                Symbol.DATAMATRIX_RECTANGLE_16 => "datamatrix_rectangle_16",
                _ => throw new ArgumentException($"Invalid symbol type: {symbol}")
            };
        }
    }

    public class SymbolOptions
    {
        public int? ErrorCorrectionLevel { get; set; }
        public int? Width { get; set; }
        public int? Height { get; set; }
        public int? Size { get; set; }
    }

    public class QRCodeOptions
    {
        public int? Size { get; set; }
        public int? ErrorCorrectionLevel { get; set; }
    }
}
