/**
 * Sass compilation and Autoprefixer
 */
module.exports = function(gulp, projectPath, themePath, config) {
    var TASK_NAME = 'browsersync',
        DEFAULT_CONFIG = {
            "host": "demo.v.ctidigital.com",
            "ssl": false
        },
        spdy = require('spdy'),
        bs = require('browser-sync').create('Dev Server'),
        vagrantPath,
        magentoCache = require('./magentocache.js'),
        bsLocalHost = '',
        bsProxy = 'https://magedemo.v.ctidigital.com',
        themeName = 'theme-magesparrow-blank/',
        blankThemePath = '../magesparrow-blank/',
        themeLocale = 'en_GB/',
        watchers = [
            {
                files: '**/*.css',
                reload: '*.css'
            },
            {
                files: '**/*.js',
                reload: '*.js',
                cacheClean: true,
                cacheParams: ['block_html', 'full_page']
            },
            {
                files: '**/fonts/**',
                cacheParams: ['full_page']
            },
            {
                files: '**/images/*.*',
                cacheClean: true,
                cacheParams: ['full_page']
            },
            {
                files: '**/*.phtml',
                cacheClean: true,
                cacheParams: ['full_page']
            },
            {
                files: '**/*.html',
                cacheClean: true,
                cacheParams: ['block_html', 'full_page']
            },
            {
                files: '**/*.xml',
                cacheClean: true,
                cacheParams: ['layout', 'full_page']
            }
        ],
        browserSync;

    /**
     * Parser for watchers[] to query specific values from the array
     *
     * @param name {string} - File type of the watchers[]
     * @param _themeName - General theme name of the project
     * @returns {object} - Result of the query
     */
    function getWatcherByName(name, _themeName) {
        var returnObj = {},
            _watcher,
            i;

        for (i = 0; i < watchers.length; i++) {
            _watcher = watchers[i];

            if ((_themeName + _watcher['files']) === name) {
                returnObj = _watcher;
            }
        }

        return returnObj;
    }

    /**
     * Strip the protocol off the URL and return only the domain name
     * @param url {string} - Domain name with protocol
     *
     * @returns {string}
     */
    function stripProtocol(url) {
        return url.replace(/(^\w+:|^)\/\//, '');
    }


    return {
        name: TASK_NAME,
        task: function getBrowserSync(done) {
            var _extend = require('merge');
            this._config = _extend.recursive(true, DEFAULT_CONFIG, config);
            this.init();
        },
        init: function () {
            var _self = this;

            themeName = projectPath + themePath;
            bsProxy = 'https://' + this._config.host;
            themeLocale = (this._config.locale) ? this._config.locale : themeLocale;
            vagrantPath = projectPath + 'vm';

            // Setup Magento Cache Clean commands/config
            magentoCache.setConfig(themeName);
            magentoCache.setHost(stripProtocol(bsProxy));
            magentoCache.setVMPath(vagrantPath);
            magentoCache.isRedis().finally(function(){
                // Add watchers and load BrowserSync
                _self.addWatchers();
                bs.init(_self.getConfig(), function (er, _bs) {
                    bsLocalHost = _bs.options.getIn(['urls', 'local']);
                    bsLocalHost = stripProtocol(bsLocalHost);
                });
            });
        },

        addWatchers: function () {
            var i,
                _watcher,
                allThemes,
                relativeThemePath;

            relativeThemePath = themePath.replace('www/app/design/', '');
            allThemes = require('path').resolve(themeName, '../') + '/';

            for (i = 0; i < watchers.length; i++) {
                _watcher = watchers[i];

               // console.log('Files to watch:' +allThemes + _watcher['files']);

                bs.watch(allThemes + _watcher['files'], {useFsEvents: true}, function (event, file) {
                    var _currentWatcher;

                    if (event === 'change') {
                        _currentWatcher = getWatcherByName(Object.keys(this._closers)[0], allThemes);

                        if (typeof _currentWatcher['cacheClean'] !== 'undefined') {
                            if (_currentWatcher['cacheClean'] === true) {
                                bs.notify('<span style="font-size:16px">🙈 &nbsp;&nbsp;Clearing Magento cache & reloading, please wait!</span>', 10000);
                                magentoCache.clear(_currentWatcher['cacheParams'], function () {
                                    bs.reload();
                                });
                            }
                        } else {
                            if (typeof _currentWatcher['reload'] !== 'undefined') {
                                if (file.indexOf('.css') >= 0) {
                                    console.log(file);
                                    var _needlePath = relativeThemePath;
                                    var _filePubPath = '//' + bsLocalHost + '/static/' + _needlePath + themeLocale +
                                        file.substr((file.indexOf(_needlePath) + _needlePath.length), (file.length - file.indexOf(_needlePath) - _needlePath.length));
                                    _filePubPath = _filePubPath.replace('/web/', '/');
                                } else {
                                    _filePubPath = file;
                                }
                                bs.notify('<span style="font-size:16px">👍 &nbsp;&nbsp;Live Reload Complete</span>', 3000);
                                bs.reload(_filePubPath);
                            } else {
                                bs.reload();
                            }
                        }
                    }
                });

                bs.watch(blankThemePath + _watcher['files'], function (event) {
                    var _currentWatcher;

                    if (event === 'change') {
                        _currentWatcher = getWatcherByName(Object.keys(this._closers)[0], blankThemePath);

                        if (typeof _currentWatcher['cacheClean'] !== 'undefined') {
                            if (_currentWatcher['cacheClean'] === true) {
                                bs.notify('<span style="font-size:16px">🙈 &nbsp;&nbsp;Clearing Magento cache & reloading, please wait!</span>', 10000);
                                bs.reload();
                                magentoCache.clear(_currentWatcher['cacheParams'], function () {
                                    bs.reload();
                                });
                            }
                        } else {
                            if (typeof _currentWatcher['reload'] !== 'undefined') {
                                bs.reload(_currentWatcher['reload']);
                            } else {
                                bs.reload();
                            }
                        }
                    }
                });
            }
        },

        getConfig: function () {

            var _c = {
                "proxy": bsProxy,
                "https": true,
                // "httpModule": 'spdy', // Disabling SPDY until this bug gets fixed to avoid ASSERTION Error https://github.com/spdy-http2/spdy-transport/issues/47
                "notify": true,
                "reloadDelay": 100,
                "reloadDebounce": 200,
                "rewriteRules": [
                    {
                        match: '"domain": ".' + stripProtocol(bsProxy) + '",',
                        replace: ''
                    }
                ]
            };

            if (typeof this._config.reloadDelay !== 'undefined') {
                _c.reloadDelay = this._config.reloadDelay;
            }

            if (typeof this._config.localhost_ssl !== 'undefined') {
                if (typeof this._config.localhost_ssl.cert !== 'undefined' && typeof this._config.localhost_ssl.key !== 'undefined') {
                    _c.https = {
                        key: this._config.localhost_ssl.key,
                        cert: this._config.localhost_ssl.cert
                    };
                }
            }


            return _c;
        }
    }
};

