    /*global $, console, alert, DataProviderHelper, FileManager */
var DataProvider = {};
    (function () {
    'use strict';
    var context   = window.parent;

    function isInvalidFormKey(response) {
        response = response.message || response;
        return typeof response === 'string' &&
            (response.indexOf('<form action="#" id="forgot_password_form"') !== -1 || response.indexOf('<form action="#" id="login_form"') !== -1);
    }

    function getSessionError() {
        var error = new SessionTimeoutError();
        error.loginUrl = context.location.href;
        return error;
    }

    function ajaxFailHandler(xhr, callback) {
        var text = xhr.responseText || xhr;
        if (isInvalidFormKey(text)) {
            callback(getSessionError());
            return true;
        } else {
            callback(new Error(text));
            return false;
        }
    }

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

    DataProvider.convertHtmlToCms = function convertHtmlToCms(fso, control) {
        if (fso.exists('page.html')) {
            var controlView = fso.read('page.html');
            if ($.trim(controlView) === '') return fso;
            if (/\{include file[\s\S]+\}/.test($.trim(controlView)) === false) {
                var controlName = control.constructorName.toLowerCase();
                var callParams = [controlName, control.id].join('_');
                var controlCall = '{include file="$tpl_dir./includes/' + callParams + '.tpl" tpl_dir=$tpl_dir}';
                fso.write('page.html', controlCall);
                fso.write('includes/' + callParams + '.tpl', controlView);
            }
        }
        return fso;
    };

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

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

    DataProvider.getTheme = function getTheme(themeName, callback) {
        $.ajax({
            url: window.pluginData.ajax,
            type: 'post',
            dataType: 'json',
            data: ({
                ajax: '1',
                action: 'getTheme',
                controller: 'AdminAjax',
                token : window.pluginData.token,
                themeName: window.pluginData.themeName,
                userThemeName: themeName
            }),
        }).done(function (response) {
            if (!callback || typeof callback !== 'function') {
                throw DataProviderHelper.getResultError('Invalid callback');
            }
            if (isInvalidFormKey(response)) {
                callback(getSessionError());
            } else if (response) {
                callback(null, response);
            } else {
                callback(DataProviderHelper.getResultError('Invalid response data'));
            }
        }).fail(function (xhr) {
            ajaxFailHandler(xhr, callback);
        });
    };

    DataProvider.doExport = function doExport(exportData, callback) {
        var request = {
            'save': {
                'post': {
                    ajax: '1',
                    action : 'export',
                    controller: 'AdminAjax',
                    token : window.pluginData.token,
                    data: JSON.stringify(exportData),
                    themeName: window.pluginData.themeName
                },
                'url': window.pluginData.ajax
            },
            'clear': {
                'post': {
                    ajax: '1',
                    action : 'clear',
                    controller: 'AdminAjax',
                    token : window.pluginData.token
                },
                'url': window.pluginData.ajax
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };

    DataProvider.save = function (saveData, callback) {
        var request = {
            'save': {
                'post': {
                    ajax: '1',
                    action : 'save',
                    controller: 'AdminAjax',
                    token : window.pluginData.token,
                    data: JSON.stringify(saveData),
                    themeName: window.pluginData.themeName,
                    domain: window.pluginData.domain,
                    isNew: window.pluginData.isNew
                },
                'url': window.pluginData.ajax
            },
            'clear': {
                'post': {
                    ajax: '1',
                    action : 'clear',
                    controller: 'AdminAjax',
                    token : window.pluginData.token
                },
                'url': window.pluginData.ajax
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };

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

    DataProvider.updatePreviewTheme = function (callback) {
        $.ajax({
            url: window.pluginData.ajax,
             data: {
                ajax: '1',
                action : 'update',
                controller: 'AdminAjax',
                token : window.pluginData.token,
                themeName : window.pluginData.themeName
            }
        })
        .done(function (response) {
            var error = null;
            if (isInvalidFormKey(response)) {
                error = getSessionError();
            }
            callback(error);
        })
        .fail(function (xhr) {
            ajaxFailHandler(xhr, callback);
        });
    };

    DataProvider.makeThemeAsActive = function makeThemeAsActive(callback) {
        $.ajax({
            type: 'post',
            url: window.pluginData.ajax,
            data: {
                ajax: '1',
                action : 'publish',
                controller: 'AdminAjax',
                token : window.pluginData.token,
                themeName: window.pluginData.themeName
            }
        }).done(function (response) {
            var error = null;
            if (isInvalidFormKey(response)) {
                error = getSessionError();
            }
            callback(error);
        }).fail(function (xhr) {
            ajaxFailHandler(xhr, callback);
        });
    };

    DataProvider.rename = function rename(themeName, callback) {
        $.ajax({
            url: window.pluginData.ajax,
            type: 'post',
            data: ({
                ajax: '1',
                action : 'rename',
                controller: 'AdminAjax',
                token : window.pluginData.token,
                newThemeName: themeName,
                themeName: window.pluginData.themeName                
            })
        }).done(function (response) {
            if (!callback || typeof callback !== 'function') {
                throw DataProviderHelper.getResultError('Invalid callback');
            }
            if (isInvalidFormKey(response)) {
                callback(getSessionError());
            } else if (response) {
                if (response.result === 'done') {
                    var currentUrl = context.location.href,
                        url = currentUrl.replace(window.pluginData.themeName, themeName);

                    callback(null);
                    context.location.replace(url);
                } else if (response.result === 'fail' && response.error) {
                    callback(DataProviderHelper.getResultError(response.error));
                } else {
                    callback(DataProviderHelper.getResultError('Invalid response result'));
                }
            } else {
                callback(DataProviderHelper.getResultError('Invalid response'));
            }
        }).fail(function (xhr) {
            ajaxFailHandler(xhr, callback);
        });
    };

    DataProvider.getInfo = function getInfo(){
        var infoData = {};
        infoData.cmsName    = 'PrestaShop';
        infoData.cmsVersion = window.pluginData.cmsVersion;
        infoData.adminPage  = window.pluginData.url.admin;
        infoData.startPage  = window.pluginData.url.preview;
        infoData.templates  = window.pluginData.templates;
        infoData.thumbnails = [{name: 'preview.jpg', width: 180, height: 226}];
        infoData.isThemeActive = window.pluginData.isActive;
        infoData.themeName = window.pluginData.themeName;

        return infoData;
    };
}());