/*globals AmCharts*/
(function () {
    'use strict';
    BEM.DOM.decl('b-map', {
        onSetMod: {
            js: function () {
                this._initBlock();
                this._setParams();
                this._addListeners();
                this._show();
            }
        },

        destruct: function () {
            if (this._map) {
                this._map.removeListener(this._map, 'dataUpdated', this._onDataUpdated);
                this._map.clearMap();
                this._map = null;
            }

            this._iRoute.un('refresh', this.refresh, this);

            this.__base.apply(this, arguments);
        },

        refresh: function () {
            var dataProvider = this._getDataProvider();
            if (dataProvider !== null) {
                this._map.dataProvider = dataProvider;
                this._map.validateData();
            }
        },

        _initBlock: function () {
            // {i-route}
            this._iRoute = BEM.blocks['i-route'].getInstance();
            // {AmMap}
            this._map = new AmCharts.AmMap();
            // {object}
            this._countryDataProviders = {
                RU: {mapVar: AmCharts.maps.russiaLow, WSID: 'ru'},
                UA: {mapVar: AmCharts.maps.ukraineLow, WSID: 'ua'},
                TR: {mapVar: AmCharts.maps.turkeyLow, WSID: 'tr'}
            };
            // {string}
            this._WSID = null;
            // {object}
            this._worldDataProvider = {
                mapVar: AmCharts.maps.worldLow,
                WSID: 'world'
            };

            var svgPath = [
                'M16', '30.534c8.027', '0', '14.534-6.507',
                '14.534-14.534c0-8.027-6.507-14.534-14.534-14.534C7.973',
                '1.466', '1.466', '7.973', '1.466', '16C1.466', '24.027',
                '7.973', '30.534', '16', '30.534zM18.335', '6.276l3.536',
                '3.538l-6.187', '6.187l6.187', '6.187l-3.536',
                '3.537l-9.723-9.724L18.335', '6.276z'
            ];
            // {object}
            this._backButton = {
                svgPath: svgPath.join(','),
                label: BEM.I18N('b-map', 'Back to countries map'),
                rollOverColor: '#cc0000',
                labelRollOverColor: '#cc0000',
                linkToObject: this._worldDataProvider,
                left: 30,
                bottom: 30,
                labelFontSize: 15
            };

            this._numberFormatter = {
                precision: -1,
                decimalSeparator: '.',
                thousandsSeparator: this.params.thousands_sep
            };
        },

        _setParams: function () {
            this._setMapParams();
            this._setProvidersParams();

            this._map.dataProvider = this._getDataProvider();
            this._onDataUpdated = this._onDataUpdated.bind(this);
        },

        _setProvidersParams: function () {
            // country
            for (var id in this._countryDataProviders) {
                this._countryDataProviders[id].images = [this._backButton];
                this._countryDataProviders[id].areas = this._genAreas('^' + id + '_[A-Z]+$');
            }
            // world
            this._worldDataProvider.images = [];
            this._worldDataProvider.areas = this._genAreas('^[A-Z]+$', true);
        },

        _setMapParams: function () {
            var map = this._map;

            map.pathToImages = '/js/ammap/images/';
            map.colorSteps = 100;
            map.zoomOnDoubleClick = false;
            map.numberFormatter = this._numberFormatter;
            map.mouseWheelZoomEnabled = true;
            map.balloon.adjustBorderColor = true;
            map.balloon.fontSize = 15;
            map.balloon.maxWidth = 600;

            map.areasSettings = {
                color: '#f5f500',
                colorSolid: '#f50000',
                balloonText: '[[title]]: [[customData]];<br />' + BEM.I18N('b-map', 'popularity') + ': [[value]]%'
            };
        },

        _getDataProvider: function () {
            var mapWSID = this._iRoute.get('map'),
                dataProvider = this._worldDataProvider;

            if (mapWSID !== undefined && mapWSID !== 'world') {
                dataProvider = this._countryDataProviders[mapWSID.toUpperCase()];
            }

            if (this._WSID !== mapWSID) {
                this._WSID = mapWSID;
                return dataProvider;
            }
            return null;
        },

        _addListeners: function () {
            this._map.addListener('dataUpdated', this._onDataUpdated);
            this._iRoute.on('refresh', this.refresh, this);
        },

        _onDataUpdated: function (e) {
            this._WSID = e.chart.dataProvider.WSID;
            this._iRoute.set('map', this._WSID);
        },

        _show: function () {
            this._map.write(this.params.name);
        },

        /**
         * @private
         * @param {string} matchStr
         * @param {boolean} hasLink
         * @rturn {array}
         **/
        _genAreas: function (matchStr, hasLink) {
            var _this = this,
                data = $.grep(this.params.data, function(v) {return v.cnt > 10 && v.am.match(matchStr);});

            function getArea(item) {
                var link = null;
                if (hasLink) {
                    link = _this._countryDataProviders[item.am] || null;
                }
                return {
                    id: item.am,
                    title: item.name,
                    value: item.pp,
                    customData: AmCharts.formatNumber(item.cnt, _this._numberFormatter),
                    linkToObject: link,
                    url: null
                };
            }

            return data.map(getArea);
        }
    }, {
        live: true
    });
})();
