


var getService = require("../libs/get-service").default;


class CONTESTS {
    constructor($el) {
        var el;

        el = $el.get(0);
        this.el = el;
        this.stateFilters = false;

        this.el = $(el);

        this.device = this.getCurrentDevice();

        this.localContestContainer = document.querySelector('.local-contests-next-list');
        this.tagFiltersContainer = document.querySelector('.local-contests-next-tags');
        this.inputTypeContainer = document.querySelector('#input-type-container');

        /* Array */
        this.tabData = [];
        this.tabMarkers = [];
        this.tabInfoWindow = [];
        this.typeFilter = [];
        this.priceFilter = [
            {label:"0€=>100€", priceMin:0, priceMax:100, checked:false},
            {label:"100€=>200€", priceMin:100, priceMax:200, checked:false},
            {label:"200€=>300€", priceMin:200, priceMax:300, checked:false},
            {label:">300€", priceMin:300, priceMax:1000000, checked:false}
        ];

        this.boxFilters = $('.local-contests-next-filters');

        this.menuFilters();
        this.loadMap();

        this.loadData();

    }

    toogleFilters(e) {
        var $t = $(this);
        if (this.stateFilters === true) {
            e.data.lcf.css('height', '90px');
            $t.removeClass('open').find('span').text('+');
            this.stateFilters = false;
            this.showFilteredList()
        }
        else {
            e.data.lcf.css('height', '700px');
            $t.addClass('open').find('span').text('-');
            this.stateFilters = true;
        }
    }

    /* ********** Menu filters ********** */

    menuFilters() {
        $('.local-contests-next-filters-btn').on("click", {lcf: this.boxFilters}, this.toogleFilters.bind(this));
    }

    buildFilters() {

    }

    loadData(context) {
        var context = this;

        // todo : use casinos.json with get-service.js
        /*$.getJSON("json/casinos.json", function (data) {

            context.tabData = data.casinos;
            context.placeMarkers();
            console.log(context)
        });*/

        getService('casinos').done(function (data) {
            context.tabData = data;
            //context.initSearchEngine();
            context.placeMarkers();

            for (var i = 0; i < data.length; i++) {

                if((JSONendpointSettings.glbWS == "" || JSONendpointSettings.glbWS == data[i].glbWS) && data[i].tournaments && data[i].tournaments[0] != undefined){
                    for (var j = 0; j < data[i].tournaments.length; j++) {
                        var dateEl = new Date(data[i].tournaments[j].date)
                        if(context.typeFilter.length>0){
                            var test = false
                            for (var k = 0; k < context.typeFilter.length; k++) {
                                if(context.typeFilter[k].label == data[i].tournaments[j].type.toLowerCase()){
                                    test = true
                                    break;
                                }
                            }
                            if(test == false){
                                context.typeFilter.push({label:data[i].tournaments[j].type.toLowerCase(),checked:false})
                            }
                        } else {
                            context.typeFilter.push({label:data[i].tournaments[j].type.toLowerCase(),checked:false})
                        }

                        // Create blocks tournaments elements

                        var li = document.createElement('li')
                        li.className += ["local-contests-next-list-item"]

                        var left = document.createElement('div')
                        left.className += ["local-contests-next-list-item-left"]

                        var title = document.createElement('div')
                        title.className += ["local-contests-next-list-item-left-title"]
                        title.innerHTML = data[i].tournaments[j].type

                        var date = document.createElement('div')
                        date.className += ["local-contests-next-list-item-left-date"]
                        if(dateEl != "Invalid Date"){
                            var strDate = dateEl.toJSON().split('T')[0].split("-").reverse().toString().replace(/,/g,"/")
                            date.innerHTML = strDate
                        }

                        var casino = document.createElement('div')
                        casino.className += ["local-contests-next-list-item-left-casino"]

                        var href = document.createElement('a')
                        href.className += [""]
                        href.innerHTML = data[i].name

                        var infos = document.createElement('div')
                        infos.className += ["local-contests-next-list-item-left-infos"]
                        infos.innerHTML = tournamentOpeningHour + dateEl.getUTCHours() + ":" + (dateEl.getUTCMinutes()<10?'0':'') + dateEl.getUTCMinutes() + " - 2:00<br />" + tournamentBuyIn + data[i].tournaments[j].registrationRight + " + " + data[i].tournaments[j].registrationFee + "€"

                        var right = document.createElement('div')
                        right.className += ["local-contests-next-list-item-right"]

                        var hrefInscription = document.createElement('a')
                        hrefInscription.className += ["local-contests-next-list-item-right-btn button-golden"]
                        hrefInscription.href = JSONendpointSettings.uri.bookingPokerTournament.url + "?c=" + data[i].glbWS
                        hrefInscription.innerHTML = tournamentRegister

                        var hrefCasino = document.createElement('a')
                        hrefCasino.className += ["local-contests-next-list-item-right-show-casino"]
                        hrefCasino.href = data[i].links.casino_home
                        hrefCasino.innerHTML = tournamentViewCasino


                        left.appendChild(title)
                        left.appendChild(date)
                        left.appendChild(casino)
                        casino.appendChild(href)
                        left.appendChild(infos)

                        right.appendChild(hrefInscription)
                        right.appendChild(hrefCasino)

                        li.appendChild(left)
                        li.appendChild(right)
                        context.localContestContainer.appendChild(li)

                        data[i].tournaments[j].elBlock = li


                    }


                }
            }


            for (var k = 0; k < context.priceFilter.length; k++) {

                var tag = document.createElement('li')
                var a = document.createElement('a')

                tag.className += ["local-contests-next-tags-item"]
                a.className += ["close"]

                tag.innerHTML = context.priceFilter[k].label

                tag.appendChild(a)
                context.tagFiltersContainer.appendChild(tag)

                tag.style.display = "none"


                context.priceFilter[k].elTag = tag
                context.priceFilter[k].elFilter = $('#input-price-container .form-inline')[k]

            }



            for (var k = 0; k < context.typeFilter.length; k++) {

                var tag = document.createElement('li')
                var a = document.createElement('a')

                tag.className += ["local-contests-next-tags-item"]
                a.className += ["close"]

                tag.innerHTML = context.typeFilter[k].label

                tag.appendChild(a)
                context.tagFiltersContainer.appendChild(tag)

                var inputTypeDiv = document.createElement('div')
                inputTypeDiv.className += ["form-inline"]

                var inputType = document.createElement('input')
                inputType.type = "checkbox"
                inputType.id = context.typeFilter[k].label.replace(/ /g,"-").replace(/\//g,"")
                inputType.value = context.typeFilter[k].label
                inputType.className += ["form-radio"]
                inputType.name = "tournois"+k
                inputType.setAttribute("data-required","required")

                var inputTypeLabel = document.createElement('label')
                inputTypeLabel.innerHTML = context.typeFilter[k].label
                inputTypeLabel.setAttribute("for",context.typeFilter[k].label.replace(/ /g,"-").replace(/\//g,""))


                inputTypeDiv.appendChild(inputType)
                inputTypeDiv.appendChild(inputTypeLabel)

                tag.style.display = "none"

                context.inputTypeContainer.appendChild(inputTypeDiv)


                context.typeFilter[k].elTag = tag
                context.typeFilter[k].elFilter = inputTypeDiv

            }

            $('#input-type-container .form-radio').each(function(index){
                $(this).on("click", function(el){
                    if(context.typeFilter[index].checked == false){
                        context.typeFilter[index].checked = true
                        context.typeFilter[index].elTag.style.display = "inline-block"
                    } else {
                        context.typeFilter[index].checked = false
                        context.typeFilter[index].elTag.style.display = "none"
                    }

                })
            })

            $('#input-price-container .form-radio').each(function(index){
                $(this).on("click", function(el){
                    if(context.priceFilter[index].checked == false){
                        context.priceFilter[index].checked = true
                        context.priceFilter[index].elTag.style.display = "inline-block"
                    } else {
                        context.priceFilter[index].checked = false
                        context.priceFilter[index].elTag.style.display = "none"
                    }

                })
            })



            var endDelimiter = document.createElement('hr')
            endDelimiter.className += ["local-contests-next-filters-separator"]

            context.inputTypeContainer.appendChild(endDelimiter)



            $('.local-contests-next-tags-item').each(function(index){
                var i = index
                $(this).find('a').on('click', function(){
                    if(i<4){
                        context.priceFilter[i].elTag.style.display = "none"
                        $(context.priceFilter[i].elFilter).find('input')[0].checked = false
                        context.priceFilter[i].checked = false
                    } else {
                        context.typeFilter[i-4].elTag.style.display = "none"
                        $(context.typeFilter[i-4].elFilter).find('input')[0].checked = false
                        context.typeFilter[i-4].checked = false
                    }

                    context.showFilteredList()
                })
            })


        });





    }

    showFilteredList(){

        var initPrice = 0
        for (var i = 0; i < this.priceFilter.length; i++) {

            var totalPrice = 0
            var isChecked = this.priceFilter[i].checked

            if(isChecked == true){
                for (var j = 0; j < this.tabData.length; j++) {


                    if((JSONendpointSettings.glbWS == "" || JSONendpointSettings.glbWS == this.tabData[j].glbWS) && this.tabData[j].tournaments && this.tabData[j].tournaments[0] != undefined){

                        for (var k = 0; k < this.tabData[j].tournaments.length; k++) {

                            totalPrice = Number(this.tabData[j].tournaments[k].registrationFee) + Number(this.tabData[j].tournaments[k].registrationRight)

                            if(totalPrice <= this.priceFilter[i].priceMax && totalPrice > this.priceFilter[i].priceMin){
                                this.tabData[j].tournaments[k].elBlock.style.display = "block"



                                this.tabData[j].marker.setVisible(true)

                            } else {
                                if(initPrice==0){
                                    this.tabData[j].tournaments[k].elBlock.style.display = "none"
                                    this.tabData[j].marker.setVisible(false)
                                }
                            }

                        }
                    }
                }
                initPrice ++
            }
        }

        var initType = 0
        for (var i = 0; i < this.typeFilter.length; i++) {

            var labelToCheck = this.typeFilter[i].label
            var isChecked = this.typeFilter[i].checked

            if(isChecked == true){
                for (var j = 0; j < this.tabData.length; j++) {

                    if((JSONendpointSettings.glbWS == "" || JSONendpointSettings.glbWS == this.tabData[j].glbWS) && this.tabData[j].tournaments && this.tabData[j].tournaments[0] != undefined){
                        for (var k = 0; k < this.tabData[j].tournaments.length; k++) {
                            if(this.tabData[j].tournaments[k].type.toLowerCase() == labelToCheck){
                                if(initPrice==0){
                                    this.tabData[j].tournaments[k].elBlock.style.display = "block"
                                    this.tabData[j].marker.setVisible(true)
                                }

                            } else {
                                if(initType==0){
                                    this.tabData[j].tournaments[k].elBlock.style.display = "none"
                                    this.tabData[j].marker.setVisible(false)
                                }
                            }
                        }
                    }
                }
                initType ++
            }
        }

        if(initType == 0 && initPrice == 0) {
            for (var j = 0; j < this.tabData.length; j++) {

                if((JSONendpointSettings.glbWS == "" || JSONendpointSettings.glbWS == this.tabData[j].glbWS) && this.tabData[j].tournaments && this.tabData[j].tournaments[0] != undefined){
                    for (var k = 0; k < this.tabData[j].tournaments.length; k++) {
                        this.tabData[j].tournaments[k].elBlock.style.display = "block"
                        this.tabData[j].marker.setVisible(true)
                    }
                }
            }
        }

    }


    /* ********** Close all InfoWindow (googlemap.infoWindow) ********** */

    initMapForDevice() {
        var map = this.map;
        (this.device != 'mobile') ? map.setZoom(6) : map.setZoom(5);
    }


    /* ********** Load MAP ******* */

    loadMap() {

        var styles = [
            {
                "featureType": "administrative",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "on"
                    }
                ]
            },
            {
                "featureType": "administrative",
                "elementType": "labels.text.fill",
                "stylers": [
                    {
                        "color": "#444444"
                    }
                ]
            },
            {
                "featureType": "administrative.province",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            },
            {
                "featureType": "administrative.locality",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "simplified"
                    }
                ]
            },
            {
                "featureType": "administrative.neighborhood",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            },
            {
                "featureType": "administrative.land_parcel",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            },
            {
                "featureType": "landscape",
                "elementType": "all",
                "stylers": [
                    {
                        "color": "#f2f2f2"
                    },
                    {
                        "visibility": "simplified"
                    }
                ]
            },
            {
                "featureType": "landscape.natural",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "simplified"
                    }
                ]
            },
            {
                "featureType": "poi",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            },
            {
                "featureType": "poi.business",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "on"
                    },
                    {
                        "saturation": "13"
                    }
                ]
            },
            {
                "featureType": "poi.sports_complex",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "on"
                    }
                ]
            },
            {
                "featureType": "road",
                "elementType": "all",
                "stylers": [
                    {
                        "saturation": "-100"
                    },
                    {
                        "lightness": "8"
                    },
                    {
                        "gamma": "2.15"
                    },
                    {
                        "hue": "#ff0000"
                    },
                    {
                        "visibility": "simplified"
                    }
                ]
            },
            {
                "featureType": "road.highway",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "simplified"
                    }
                ]
            },
            {
                "featureType": "road.arterial",
                "elementType": "labels.icon",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            },
            {
                "featureType": "transit",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "off"
                    }
                ]
            },
            {
                "featureType": "water",
                "elementType": "all",
                "stylers": [
                    {
                        "visibility": "on"
                    },
                    {
                        "color": "#acbcc9"
                    }
                ]
            }
        ]

        var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"});

        /* Map options */
        this.mapOptions = {
            mapTypeControl: false,
            center: {
                lat: 47,
                lng: 2
            },
            zoom: 6,
            mapTypeControlOptions: {
                mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
            }
        };

        this.icon = {
            url: 'img/skin/marker-dot.png',
            anchor: new google.maps.Point(14, 40),
            scaledSize: new google.maps.Size(28, 40)
        };

        this.map = new google.maps.Map(document.getElementById('contests-map'), this.mapOptions);
        this.map.mapTypes.set('map_style', styledMap);
        this.map.setMapTypeId('map_style');

        this.initMapForDevice();
    }

    placeMarkers() {

        var self = this;

        var infoWindowContent = [];





        for (var i = 0; i < this.tabData.length; i++) {

            if((JSONendpointSettings.glbWS == "" || JSONendpointSettings.glbWS == this.tabData[i].glbWS) && this.tabData[i].tournaments != undefined){
                if(this.tabData[i].tournaments.length>0){
                    var context = this;

                    var location = new google.maps.LatLng(this.tabData[i].latitude, this.tabData[i].longitude);

                    this.tabData[i].marker = new google.maps.Marker({
                        position: location,
                        icon: this.icon,
                        map: this.map,
                        title: this.tabData[i].label,
                        size : new google.maps.Size(420, 680)
                    });

                    this.tabData[i].marker.id = this.tabData[i].idCasino;
                    this.tabMarkers.push(this.tabData[i].marker);

                    google.maps.event.addListener(this.tabData[i].marker, 'click', (function (marker, i) {

                        return function () {
                            // SHOW CONTESTS ...
                            //if(context.device === 'mobile') {
                            var offset = $('.local-contests-next-title').offset();
                            $("html, body").animate({scrollTop: offset.top - 54}, 400);
                            //}
                        }

                    })(this.tabData[i].marker, i));
                }
            }




        }

    }

    /* ********** getCurrentDevice ********** */

    getCurrentDevice() {
        return window.getComputedStyle(document.querySelector("body"), "::before").getPropertyValue("content").replace(/"|'/g, '');
    }

}
export default CONTESTS;
