// com.tts.initial.html5.rotatabletextbox
define(["jquery"], function (jq) {

    "use strict";

    var RotatableTextBoxBuilder = function (options) {
        function createTextContent() {
            var textContainer = jq(document.createElement("div"))
                    .css({
                        "width": "100%",
                        "padding-left": (options.textParams.paddingLeft - parseInt(options.autoform.borderSize)) + "px",
                        "padding-right": (options.textParams.paddingRight - parseInt(options.autoform.borderSize)) + "px",
                        "text-align": options.textParams.orientation
                    })

            if (options.textParams.verticalAlignment === "middle" && !options.autoAdjustHeight) {
                textContainer.css({
                    "vertical-align": "middle",
                    "display": "table-cell"
                });
            }else {
                textContainer.css({
                    "position": "absolute",
                    "padding-top": options.textParams.paddingTop + "px",
                    "padding-bottom": options.textParams.paddingBottom + "px"
                });

                textContainer.css(options.textParams.verticalAlignment, "0");

                if (options.textParams.orientation === "right") {
                    textContainer.css(options.textParams.orientation, "0");
                }
            }

            textContainer.html(options.text.content);

            return textContainer;
        }

        function createTextbox() {
            var textbox = jq(document.createElement("div"))
                    .css({
                        "width": "100%",
                        "background-color": options.autoform.backgroundColor,
                        "font-family": options.textParams.fontFamily,
                        "font-size": options.textParams.fontSize + "px",
                        "font-weight": "normal",
                        "font-style": "normal",
                        "color": options.textParams.fontColor,
                        "line-height": options.textParams.fontSize + "px",
                        "padding-top": (options.textParams.paddingTop - parseInt(options.autoform.borderSize)) + "px",
                        "padding-bottom": (options.textParams.paddingBottom - parseInt(options.autoform.borderSize)) + "px",
                        "box-sizing": "border-box",
                        "border": (options.autoform.borderSize > 0) ? options.autoform.borderSize + "px solid " + options.autoform.borderColor : "0",
                        "-webkit-transform": "rotate(" + parseInt(options.degree) + "deg)",
                        /* Saf3.1+, Chrome */
                        "-moz-transform": "rotate(" + parseInt(options.degree) + "deg)",
                        /* FF3.5+ */
                        "-ms-transform": "rotate(" + parseInt(options.degree) + "deg)",
                        /* IE9 */
                        "-o-transform": "rotate(" + parseInt(options.degree) + "deg)",
                        /* Opera 10.5 */
                        "transform": "rotate(" + parseInt(options.degree) + "deg)"
                    })

            if (options.textParams.bold) { textbox.css({ "font-weight": "bold" }) };
            if (options.textParams.italic) { textbox.css({ "font-style": "italic" }) };
            if (options.textParams.underline) { textbox.css({ "text-decoration": "underline" }) };

            if (options.textParams.verticalAlignment === "middle" && options.autoAdjustHeight === 0) {
                textbox.css("display", "table");
            }

            if (options.autoAdjustHeight === 1) {
                textbox.css({
                    "padding-top": (options.textParams.paddingTop - parseInt(options.autoform.borderSize)) + "px",
                    "padding-bottom": (options.textParams.paddingBottom - parseInt(options.autoform.borderSize)) + "px",
                    "text-align": options.textParams.orientation
                })
                .html(options.text.content);
            } else {
                textbox.append(createTextContent());
            }

            return {
                getTextboxDiv: function () {
                    return textbox;
                },
                setCss: function (params) {
                    textbox.css(params);
                }
            };
        }

        return {
            build: createTextbox
        };

    };

    /**
	 * @constructor
	 */
    return function (context, metadata) {
        var shellElement,
            scParams = metadata.parameters,
            isInAuthoringMode = false,
            isStandardPlayer = context.getPlayerName() === "standard",
            textbox;

        function asRgbaValue(colorParameterName, defaultColor, transparencyParameterName) {

            var color = hexToRgb(scParams.get(colorParameterName, defaultColor)),
                alpha = asAlpha(scParams.asNumber(transparencyParameterName, 0));

            return "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + alpha + ")";
        }

        function hexToRgb(hex) {
            var parsingResult = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
            return parsingResult ? {
                r: parseInt(parsingResult[1], 16),
                g: parseInt(parsingResult[2], 16),
                b: parseInt(parsingResult[3], 16)
            } : {
                r: 0,
                g: 0,
                b: 0
            };
        }

        function asAlpha(percentValue) {
            return (100 - percentValue) / 100;
        }

        function getFontStyle(paramValue) {
            switch (paramValue) {
                case 2:
                    return "\"Times New Roman\", Times, serif";
                case 3:
                    return "Verdana, Geneva, sans-serif";
                case 4:
                    return "\"Courier New\", Courier, monospace";
                default:
                    return "Arial, Helvetica, sans-serif";
            }
        }

        function getCoreCss() {

            var coreStyles = {
                "cursor": "default"
            };

            if (!isStandardPlayer) {
                coreStyles["width"] = "100%";
                coreStyles["height"] = "100%";
            }

            return coreStyles;
        }

        function createComponent() {
            textbox = new RotatableTextBoxBuilder({
                width: metadata.getWidth(),
                height: metadata.getHeight(),
                degree: scParams.get("degree", "0").replace(/,/g, '.'),
                autoAdjustHeight: scParams.asNumber("auto-adjust-height", "1"),
                autoform: {
                    borderSize: scParams.asNumber("border-size", "1"),
                    borderColor: asRgbaValue("border-color", "#b1bdc7", "border-transparency"),
                    backgroundColor: asRgbaValue("background-color", "#ffffff", "background-transparency")
                },
                text: {
                    content: scParams.get("text", "Lorem ipsum ...")
                },
                textParams: {
                    fontFamily: getFontStyle(scParams.asNumber("font-family", "1")),
                    fontSize: scParams.asNumber("font-size", "14"),
                    fontColor: scParams.get("color", "#142534"),
                    bold: scParams.asBool("bold", false),
                    italic: scParams.asBool("italic", false),
                    underline: scParams.asBool("underline", false),
                    orientation: scParams.get("text_orientation", "left"),
                    verticalAlignment: scParams.get("text_vertical_align", "top"),
                    paddingLeft: Math.abs(scParams.asNumber("padding-left", "10")),
                    paddingRight: Math.abs(scParams.asNumber("padding-right", "10")),
                    paddingTop: Math.abs(scParams.asNumber("padding-top", "12")),
                    paddingBottom: Math.abs(scParams.asNumber("padding-bottom", "6"))
                }
            }).build();

            shellElement.css(getCoreCss())
                .append(textbox.getTextboxDiv());

            if (scParams.asNumber("auto-adjust-height", "1") === 1) {
                shellElement.css({
                    "height": textbox.getTextboxDiv().outerHeight(true) + "px"
                })
            } else {
                textbox.setCss({
                    "height": "100%"
                })
            }

            if (isInAuthoringMode) {
                createAuthoringShield(shellElement);
            }
        }

        function createAuthoringShield(shellElement) {
            shellElement.append(jq(document.createElement("div"))
                .css({
                    "position": "absolute",
                    "left": 0,
                    "top": 0,
                    "background-color": "#ffffff",
                    "opacity": "0",
                    "width": "100%",
                    "height": "100%",
                    "z-index": "9999"
                }));
        }

		// revealing public API
		return {
            onLoading: function () {
                shellElement = jq(context.getElement());

                isInAuthoringMode = !!context.stage.isInAuthoringMode();

                createComponent();
            }
        };
	};
});
