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

    "use strict";

    function RotatableTextBoxBuilder(metadata) {

        var parameters = metadata.parameters,
            fonts = [
                'Arial, Helvetica, sans-serif',
                '"Times New Roman", Times, serif',
                'Verdana, Geneva, sans-serif',
                '"Courier New", Courier, monospace',
                'Roboto, "Helvetica Neue", Helvetica, Arial, sans-serif',
                '"Droid Serif", "Times New Roman", Times, serif'
            ];

        function getFont(index) {
            var fontIndex = (index > 0 && index < fonts.length) ? index - 1 : 0;
            return fonts[fontIndex];
        }

        function asRgbaValue(colorParameterName, defaultColor, transparencyParameterName) {

            var color = hexToRgb(parameters.get(colorParameterName, defaultColor)),
                alpha = asAlpha(parameters.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 createRotatableTextbox() {

            var fontSize = parameters.get("font-size", "14"),
                borderSize = parameters.get("border-size", "1"),
                rotation = parameters.get("degree", "0"),
                textbox;

            rotation = rotation.replace(/,/g, '.');

            textbox = jq(document.createElement("div"))
                .css({
                    "width": "100%",
                    "background-color": asRgbaValue("background-color", "#cccccc", "background-transparency"),
                    "font-family": getFont(parameters.asNumber("font-family", 0)),
                    "font-size": fontSize + "px",
                    "font-weight": "normal",
                    "font-style": "normal",
                    "color": parameters.get("color", "#919191"),
                    "line-height": fontSize + "px",
                    "padding-left": (parameters.asNumber("padding-left", "10") - parseInt(borderSize)) + "px",
                    "padding-right": (parameters.asNumber("padding-right", "10") - parseInt(borderSize)) + "px",
                    "padding-top": (parameters.asNumber("padding-top", "12") - parseInt(borderSize)) + "px",
                    "padding-bottom": (parameters.asNumber("padding-bottom", "6") - parseInt(borderSize)) + "px",
                    "text-align": parameters.get("text_orientation", "center"),
                    "box-sizing": "border-box",
                    "border": (borderSize > 0) ? borderSize + "px solid " + asRgbaValue("border-color", "#98a7b5", "border-transparency") : "0",
                    "-webkit-transform": "rotate(" + parseInt(rotation) + "deg)",
                    /* Saf3.1+, Chrome */
                    "-moz-transform": "rotate(" + parseInt(rotation) + "deg)",
                    /* FF3.5+ */
                    "-ms-transform": "rotate(" + parseInt(rotation) + "deg)",
                    /* IE9 */
                    "-o-transform": "rotate(" + parseInt(rotation) + "deg)",
                    /* Opera 10.5 */
                    "transform": "rotate(" + parseInt(rotation) + "deg)"
                })
                .html(parameters.get("text", ""));

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

            return textbox;
        }

        return {

            build: function () {

                var textboxDiv = createRotatableTextbox();

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

    /**
	 * @constructor
	 */
    return function (context, metadata) {

        // declare private members
        var parameters = metadata.parameters,
            isStandardPlayer = context.getPlayerName() === "standard",
            textbox,
            textboxDiv,
            shellElement;

        function createComponent() {
            var renderedSize,
                renderedHeight,
                renderedWidth;

            textbox = new RotatableTextBoxBuilder(metadata).build();
            shellElement = jq(context.getElement());
            textboxDiv = textbox.getTextboxDiv();

            shellElement.css(getCoreCss())
                .append(textboxDiv);

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

            /*shellElement.css({
                "width" : textboxDiv[0].getBoundingClientRect().width + "px",
                "height": textboxDiv[0].getBoundingClientRect().height + "px"
            })*/

            renderedHeight = (((textboxDiv[0].getBoundingClientRect().height - metadata.getHeight()) * 100) / textboxDiv[0].getBoundingClientRect().height) / 2;
            shellElement.css({
                "padding-top": renderedHeight + "%",
                "padding-bottom": renderedHeight + "%"
            })

            if (context.stage.isInAuthoringMode()) {
                shellElement.prepend( createAuthoringShield() );
            }
        }

        function getRenderedSize(elem) {
            var renderedHeight,
                renderedWidth,
                clonedElem = elem.clone();

            clonedElem.appendTo('body');
            renderedHeight = clonedElem[0].getBoundingClientRect().height;
            renderedWidth = clonedElem[0].getBoundingClientRect().width;
            /*renderedHeight = clonedElem.innerHeight();
            renderedWidth = clonedElem.innerWidth();*/
            clonedElem.remove();

            return {
                "width": renderedWidth,
                "height": renderedHeight
            }
        }

        function fixSizeAndPosition() {
            /*textboxDiv.css('width', textboxDiv.width());
            textboxDiv.css('height', textboxDiv.height());
            textboxDiv.css('margin-bottom', -textboxDiv.width());
            shellElement.css('width', textboxDiv.width());
            shellElement.css('height', textboxDiv.height());*/
        }

        function getCoreCss(){

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

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

            return coreStyles;
		}

		function createAuthoringShield() {
			return jq( document.createElement("div") )
				.css({
					"width" : "100%",
					"height" : "100%",
					"position" : "absolute",
					"opacity" : "0.15",
					"background-image" : parameters.get("background-transparency", "0" ) === 100 ? "url(\"" + context.getPath() + "invis.png\")" : ""
				});
		}

		// revealing public API
		return {
            onLoading: function () {
                context.page.event.bindOnEnter(this);
                createComponent();
            },
            onEnterPage: fixSizeAndPosition
        };
	};
});
