<link rel="import" href="../../bower_components/polymer/polymer.html" />

<link rel="import" href="../../bower_components/paper-material/paper-material.html" />

<link rel="import" href="../../bower_components/paper-dropdown-menu/paper-dropdown-menu.html">
<link rel="import" href="../../bower_components/paper-menu/paper-menu.html">
<link rel="import" href="../../bower_components/paper-item/paper-item.html">

<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../bower_components/iron-icons/iron-icons.html">
<link rel="import" href="../../bower_components/iron-icon/iron-icon.html">

<link rel="import" href="../../bower_components/paper-input/paper-textarea.html">

<link rel="import" href="../../bower_components/paper-button/paper-button.html">

<link rel="import" href="../items-vslider-controllet/items-vslider-controllet.html" />

<script src="../../../DEEPCLIENT/js/deepClient.js"></script>

<dom-module id="datalet-selection-controllet">

    <template>

        <style is="custom-style">

            #datalet_selection_container {
                display: flex;
                font-family: 'Roboto', 'Helvetica Neue', Helvetica, Arial, sans-serif;
                font-size: 16px;
                margin-top: 8px;
            }

            #datalet_selection_inputs {
                position: relative;
                height: 100vh;
                margin-left: 32px;
                width: 344px;
            }

            #datalet_selection_labels {
                position: relative;
                height: 100vh;
                margin-left: 32px;
                width: 344px;
            }

            #datalet_selection_column {
                position: relative;
                width: 100%;
                margin-left: 32px;
            }

            #datalet_selection_datalet {
                position: relative;
                height: 100vh;
                width: 100%;
                /*margin-left: 32px;*/
                /*margin-top: 32px;*/
                /*margin-bottom: 32px;*/
            }

            #datalet_selection_comment{
                width: 100%;
                margin-bottom: 32px;
            }

            #datalet_selection_datalet_placeholder {
                padding: 16px;
            }

            .inputs{
                position: relative;
                /*margin-left: 16px;*/
                /*margin-right: 16px;*/
            }

            .input_name{
                height: 16px;
                padding: 16px;
                /*background-color: #B6B6B6;*/

                background-color: #2196F3;
                color: #FFFFFF;
                font-weight: 700;
            }

            .input_header{
                /*height: 16px;*/
                padding: 16px;
                background-color: #B6B6B6;
                text-align: center;
                font-weight: 700;
            }

            .info_button {
                position: absolute;
                top: 4px;
                right: 0px;
            }

            paper-textarea {
                height: 48px;
                padding: 0px 8px;
                --paper-input-container-focus-color: #2196F3;
            }

            paper-dropdown-menu {
                height: 48px;
                padding: 0px 8px;
                --paper-input-container-focus-color: #2196F3;
            }

            paper-item.iron-selected {
                background-color: #2196F3;
                color: #FFFFFF;
            }

            paper-icon-button {
                /*color: #2196F3;*/
                color: #FFFFFF;
                --paper-icon-button-ink-color: #2196F3;
                /*padding: 0px;*/
            }

            paper-button {
                /*display: block;*/
                position: absolute;
                bottom: 16px;
                right: 11px;

                height: 48px;
                width: 172px;
                background-color: #00BCD4;
                color: white;
                font-weight: 700;
                padding: 16px;
            }

            paper-button:hover {
                background-color: #00AABF;
            }

            paper-button[disabled] {
                background-color: #B6B6B6;
            }
        </style>

        <iron-ajax id="selectedDatalet_request" on-response="_handleSelectedDatalet"></iron-ajax>

        <div id="datalet_selection_container">
            <items-vslider-controllet datalets-list-url={{dataletsListUrl}}></items-vslider-controllet>


            <paper-material id="datalet_selection_inputs" elevation="5">
                <div class="input_header">INPUTS</div>
                <template is="dom-repeat" items="{{inputs}}" index-as="index">
                    <div class="inputs">
                        <div class="input_name">
                            {{item.name}}
                            <div class="info_button">
                                <paper-icon-button id="info_button" on-click="_showInfo" icon="info-outline" title="{{item.name}} info"></paper-icon-button>
                            </div>
                        </div>
                        <paper-dropdown-menu no-label-float label={{item.name}}>
                            <paper-menu class="dropdown-content">
                                <template is="dom-repeat" items={{selectableFields}}>
                                    <paper-item id={{index}} on-tap="_loadDatalet">{{item}}</paper-item>
                                </template>
                            </paper-menu>
                        </paper-dropdown-menu>
                    </div>
                </template>
            </paper-material>

            <paper-material id="datalet_selection_labels" elevation="5">
                <div class="input_header">LABELS</div>
                <template is="dom-repeat" items="{{labels}}" index-as="index">
                    <div class="inputs">
                        <div class="input_name">
                            {{item.name}}
                            <div class="info_button">
                                <paper-icon-button id="info_button" on-click="_showInfo" icon="info-outline" title="{{item.name}} info"></paper-icon-button>
                            </div>
                        </div>
                        <paper-textarea no-label-float label={{item.name}}></paper-textarea>
                    </div>
                </template>
            </paper-material>


            <div id="datalet_selection_column">
                <paper-material id="datalet_selection_comment" elevation="5">
                    <div class="input_header">COMMENT</div>
                    <paper-textarea id="comment" no-label-float maxlength="100" label="comment (max 100 characters)"></paper-textarea>
                </paper-material>

                <paper-material id="datalet_selection_datalet" elevation="5">
                    <div class="input_header">DATALET PREVIEW</div>
                    <div id="datalet_selection_datalet_placeholder"></div>

                </paper-material>

                <paper-button id="add_button" disabled raised on-click="_addDatalet">ADD DATALET</paper-button>

            </div>

        </div>

    </template>

    <script>

        Polymer({

            is : 'datalet-selection-controllet',

            properties : {

                deepUrl : {
                    type : String,
                    value : undefined
                },

                dataletsListUrl : {
                    type : String,
                    value : undefined
                },

                selectedDatalet : {
                    type  : String,
                    value : undefined
                },

                inputs : {
                    type : Array,
                    value : []
                },

                labels : {
                    type : Array,
                    value : []
                },

                fields : {
                    type : Array,
                    value : []
                },

                selectedFields : {
                    type : Array,
                    value : []
                },

                selectableFields : {
                    type : Array,
                    value : []
                },

                dataUrl : {
                    type  : String,
                    value : undefined
                }

            },

            listeners: {
                'items-vslider-controllet_selected-datalet': '_dataletSelected'
//                'tree-view-controllet_selected-fields': '_updateSelectedFields'
            },

            ready : function() {
                this._resize();
                $(this.$.datalet_selection_inputs).perfectScrollbar();
                $(this.$.datalet_selection_labels).perfectScrollbar();
                $(this.$.datalet_selection_datalet).perfectScrollbar();

                this.selectableFields = this._copy(this.fields);
            },

            attached : function() {
                this._resize();
                var that = this;
                window.addEventListener("resize", function() { that._resize(); });
            },

            setFields : function(fields) {
                this.fields = fields;
            },

            _dataletSelected : function(e){
                this.$.add_button.setAttribute("disabled", "true");

                this.selectedDatalet = e.detail.datalet;
                this.inputs = [];
                this.labels = [];

                if(this.selectedDatalet){
                    this.$.selectedDatalet_request.url = this.deepUrl + e.detail.datalet + "-datalet";
                    this.$.selectedDatalet_request.generateRequest();
                }
//                else {
//                    this.inputs = [];
//                    this.labels = [];
//                }

                this.$.datalet_selection_datalet_placeholder.innerHTML = "";
                this.selectedFields = [];
                this.selectableFields =  this._copy(this.fields);

//                this.async(function(){this._loadPreview();}, 1000);
                this._loadPreview();
            },

            _handleSelectedDatalet : function(e){


//                console.log(e.detail.response.idm.inputs);
//                console.log(e.detail.response.idm.inputs.layouts.input);
                var inputs = e.detail.response.idm.inputs.input;
                var labels = e.detail.response.idm.inputs.layouts.input;

                if(inputs.constructor == Object) {//not Array && inputs.input.selection == "*"
                    var name = inputs.name;
                    var description = inputs.description;
                    var selection = inputs.selection;
                    inputs = [];
                    for(var i in this.fields)
                        inputs.push({name: name + " " + i, description: description, selection: selection});

                }

                this.inputs = inputs;
                this.labels = labels;
            },

            _copy : function(o) {
                var out, v, key;
                out = Array.isArray(o) ? [] : {};
                for (key in o) {
                    v = o[key];
                    out[key] = (typeof v === "object") ? this._copy(v) : v;
                }
                return out;
            },

            _loadDatalet : function(e){
                var selectedFields = this._copy(this.selectedFields);
                var selectableFields = this._copy(this.selectableFields);

                if($(e.target).parents("paper-dropdown-menu")[0].selectedItem) {
                    var prevSelected = $(e.target).parents("paper-dropdown-menu")[0].selectedItem.innerText;
                    var index = this.selectedFields.indexOf(prevSelected);
                    selectedFields.splice(index, 1);
//                    selectableFields.push(prevSelected);
                }

                var selected = e.target.innerText;
//                var index = this.selectableFields.indexOf(selected);
//                selectableFields.splice(index, 1);
                selectedFields.push(selected);

                this.selectedFields = selectedFields;
                this.selectableFields = selectableFields;

                console.log(this.selectedFields);
                console.log(this.selectableFields);

                var load = false;
                if(this.selectedFields.length > 0 && this.inputs[0].selection == "*")
                    load = true;
                else if(this.selectedFields.length == this.inputs.length)
                    load = true;

                if(load){
                    var params = {'data-url' : this.dataUrl};

                    var dataletParams ={
                        component   : this.selectedDatalet+"-datalet",
                        params      : params,
                        fields      : this.selectedFields,
                        placeHolder : datalet_selection_datalet_placeholder
                    };

                    ComponentService.deep_url = this.deepUrl;
                    ComponentService.getComponent(dataletParams);

                    this.async(function(){this.$.add_button.removeAttribute("disabled");}, 1111);
                }

//                this.$.datalet_selection_datalet_placeholder.innerHTML = "<datatable-datalet data-url=\"http://ckan.routetopa.eu/api/action/datastore_search?resource_id=73e02092-85a1-434e-85fe-0c9a43aa9a52&amp;limit=10000\" fields='[\"result,records,Lat\",\"result,records,Lng\"]'>we";
//                this.$.datalet_selection_datalet_placeholder.innerHTML = "<"+this.selectedDatalet+"-datalet data-url=\""+this.dataUrl+"\" fields='"+JSON.stringify(this.fields)+"'></"+this.selectedDatalet+">";

//                $("#base_datalet_container").html("");
                $("#base_datalet_container").css('visibility','hidden');
                $("#base_datalet_container").css('padding','0px');
                $("#base_datalet_container").css('height','0px');
//                console.log($("#base_datalet_container"));
            },

            _addDatalet : function(){console.log("we");

                var data = {
                    dataUrl : this.dataUrl,
//                    params :  this.paramsFields,
                    params :  {'data-url' : this.dataUrl},
                    fields :  this.selectedFields,
                    datalet : this.selectedDatalet+"-datalet",
                    comment : this.$.comment.value,
                    staticData : JSON.stringify(this.$.datalet_selection_datalet_placeholder.children[1].behavior.data)
                }

                this.fire('data-sevc-controllet.dataletCreated', {data : data});

            },

            _resize : function(){
                var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0) - 16;
                h = h - 64 - 8; //height with page scroller

                $("#items_vslider_container").height(h);//vslider controllet

                $("#datalet_selection_inputs").height(h);
                $("#datalet_selection_labels").height(h);
                $("#datalet_selection_datalet").height(h-132);
            }

        });

    </script>

</dom-module>