/*global $, DataProviderHelper, SessionTimeoutError, ServerPermissionError */

var DataProvider = {};

(function () {
    'use strict';
    var context = window.parent;

    DataProvider.validateResponse = function validateResponse(xhr) {
        var error = DataProviderHelper.validateRequest(xhr);
        if (!error) {
            var responseText = xhr.responseText;
            if (typeof responseText === 'string') {
                if (responseText.indexOf('id="user-login-form"') !== -1 ||
                    responseText.indexOf('id="user-login"') !== -1) {
                    error = new SessionTimeoutError();
                    error.loginUrl = context.location.href;
                } else {
                    try {
                        var obj = JSON.parse(responseText);
                        if (obj.result === 'fail' && obj.type === 'permission') {
                            error = new ServerPermissionError(obj.error);
                        }
                    } catch (e) {
                    }
                }
            }
        }
        return error;
    };

    function addQueryArg(uri, key, value) {
        var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
        var separator = uri.indexOf('?') !== -1 ? "&" : "?";
        if (uri.match(re))
            return uri.replace(re, '$1' + key + "=" + value + '$2');
        return uri + separator + key + "=" + value;
    }

    function ajaxFailHandler(url, xhr, status, callback) {
        var error = DataProvider.validateResponse(xhr);
        if (!error) {
            error = DataProviderHelper.createCmsRequestError(url, xhr, status);
        }
        callback(error);
    }

    function createChunkedRequest(action, data) {
        return {
            'save': {
                'post': {
                    data: JSON.stringify(data),
                    action : action,
                    uid: window.pluginData.uid,
                    themeName: window.pluginData.themeName
                },
                'url': window.pluginData.url.process_request
            },
            'clear': {
                'post': {
                    action : 'clear',
                    uid: window.pluginData.uid
                },
                'url': window.pluginData.url.process_request
            },
            'errorHandler': DataProvider.validateResponse,
            'zip': true,
            'blob': true
        };
    }

    function doRequest(data, onError, onSuccess) {
        if (!onError || typeof onError !== 'function') {
            throw DataProviderHelper.getResultError('Invalid callback');
        }

        $.ajax({
            url: window.pluginData.url.process_request,
            type: 'post',
            dataType: 'json',
            data: jQuery.extend({
                uid: window.pluginData.uid
            }, data)
        }).done(function requestSuccess(response, status, xhr) {
            var error = DataProvider.validateResponse(xhr);
            if (error) {
                onError(error);
            } else if (response.result === 'done') {
                if (typeof onSuccess === 'undefined') {
                    onError(error, response);
                } else {
                    onSuccess(response);
                }
            } else {
                var invalidResponseError = DataProviderHelper.createCmsRequestError(window.pluginData.url.process_request, xhr, status, (data.action || '') + ' server error: ' + JSON.stringify(response));
                onError(invalidResponseError);
            }
        }).fail(function requestFail(xhr, status) {
            ajaxFailHandler(window.pluginData.url.process_request, xhr, status, onError);
        });
    }

    function reloadInfo(action, callback) {
        if (!callback || typeof callback !== 'function') {
            throw DataProviderHelper.getResultError('Invalid callback');
        }

        $.ajax({
            url: window.pluginData.url.process_request,
            type: 'post',
            data: ({
                action : action,
                uid: window.pluginData.uid,
                themeName: window.pluginData.themeName
            })
        }).done(function reloadInfo(data, status, xhr) {
            var error = DataProvider.validateResponse(xhr);
            if (!error) {
                try {
                    $.each(data, function(key, value) {
                        window.pluginData[key] = value;
                    });
                } catch(e) {
                    error = new Error(e);
                    error.args = { parseArgument: data };
                }
            }
            callback(error, JSON.stringify(data));
        }).fail(function reloadInfo(xhr, status) {
            ajaxFailHandler(window.pluginData.url.process_request, xhr, status, callback);
        });
    }

    DataProvider.backToAdmin = function backToAdmin() {
        window.location = window.pluginData.url.admin;
    };

    DataProvider.getMaxRequestSize = function getMaxRequestSize() {
        return window.pluginData.maxRequestSize;
    };

    DataProvider.getAllCssJsSources = function getAllCssJsSources() {
        return window.pluginData.cssJsSources;
    };

    DataProvider.getMd5Hashes = function getMd5Hashes() {
        return window.pluginData.md5Hashes;
    };

    DataProvider.getTheme = function getTheme(data, callback) {
        var url = window.pluginData.url.process_request;
        data.action = 'download';
        data.srcTheme = window.pluginData.themeName;
        data.uid = window.pluginData.uid;
        $.each(data, function(key, value) {
            url = addQueryArg(url, key, value);
        });
        callback(null, url);
    };

    DataProvider.doExport = function doExport(exportData, callback) {
        DataProviderHelper.chunkedRequest(createChunkedRequest('export', exportData), callback);
    };

    DataProvider.save = function (saveData, callback) {
        DataProviderHelper.chunkedRequest(createChunkedRequest('save', saveData), callback);
    };

    DataProvider.load = function() {
        return window.pluginData.project.projectData;
    };

    DataProvider.updatePreviewTheme = function updatePreviewTheme(callback) {
        doRequest({action: 'update', themeName: window.pluginData.themeName}, callback);
    };

    DataProvider.makeThemeAsActive = function makeThemeAsActive(callback, id) {
        var data = {action: 'activate', themeName: window.pluginData.themeName};
        if (typeof id !== 'undefined') {
            data.newName = id;
        }
        doRequest(data, callback);
    };

    DataProvider.removeTheme = function removeTheme(id, callback) {
        doRequest({action: 'remove', removedName: id}, callback);
    };

    DataProvider.copyTheme = function copyTheme(id, newName, callback) {
        var data = {action: 'copy', themeName: id};
        if (typeof newName !== 'undefined') {
            data.newName = newName;
        }
        doRequest(data, callback);
    };

    DataProvider.renameTheme = function renameTheme(themeName, newName, callback) {
        doRequest({action: 'rename', themeName: themeName, newName: newName}, callback, function(response) {
            callback(null, context.location.href.replace(new RegExp('theme=' + window.pluginData.themeName), 'theme=' + newName));
        });
    };

    DataProvider.rename = function rename(newName, callback) {
        DataProvider.renameTheme(window.pluginData.themeName, newName, callback);
    };

    DataProvider.canRename = function canRename(themeName, callback) {
        doRequest({action: 'canrename', themeName: window.pluginData.themeName, newName: themeName}, callback, function(response) {
            if (response.message === '') {
                callback(null, true);
            } else {
                callback(null, false, response.message);
            }
        });
    };

    DataProvider.themeNameValidation = function validation(name, callback) {
        doRequest({action: 'validation', themeName: window.pluginData.themeName, newName: name}, callback, function(response) {
            if (response.message === '') {
                callback(null);
            } else {
                callback(null, response.message);
            }
        });
    };

    DataProvider.getFiles = function getFiles(mask, filter, callback) {
        doRequest({action: 'get_files', themeName: window.pluginData.themeName, mask: mask || '*', filter: filter || ''}, callback, function(response) {
            callback(null, response.files);
        });
    };

    DataProvider.setFiles = function setFiles(files, callback) {
        DataProviderHelper.chunkedRequest(createChunkedRequest('set_files', files), callback);
    };

    DataProvider.zip = function zip(data, callback) {
        DataProviderHelper.chunkedRequest(createChunkedRequest('fso_zip', data), callback);
    };

    DataProvider.reloadTemplatesInfo = function reloadTemplatesInfo(callback) {
        reloadInfo('refresh_templates', callback);
    };
    
    DataProvider.reloadThemesInfo = function reloadTemplatesInfo(callback) {
        reloadInfo('refresh_themes', callback);
    };
    
    DataProvider.getInfo = function getInfo(){
        return {
            cmsName: 'Drupal8',
            cmsVersion: window.pluginData.cmsVersion,
            adminPage: window.pluginData.url.admin,
            startPage: window.pluginData.url.preview,
            uploadImage: window.pluginData.url.upload_image,
            uploadTheme: window.pluginData.url.upload_theme,
            templates: $.extend({}, window.pluginData.templates),
            canDuplicateTemplatesConstructors: $.extend({}, window.pluginData.canDuplicateTemplatesConstructors),
            unZip: window.pluginData.url.unzip,
            themes: window.pluginData.themes,
            thumbnails: [{name: 'screenshot.png', width: 300, height: 220, version: '8.x'}],
            isThemeActive: window.pluginData.isActive,
            themeName: window.pluginData.themeName,
            includeEditorSupport: true,
            pathToManifest: '/export/themler.manifest'
        };
    };

    DataProvider.getVersion = function () {
        return "0.0.2";
    };

    DataProvider.escapeCustomCode = function (content) {
        return content;
    };

    if (!window.pluginData || !window.pluginData.project) {
        var url = window.location.href;
        if (url.indexOf('#') !== -1)
            url = url.substring(0, url.indexOf('#'));
        window.location.href = addQueryArg(url, 'noCache', Math.floor(Math.random() * 1e5) + '');
    }
}());