var DataProvider = (function () {
    'use strict';

    var context   = window,
        config    = context.config,
        provider  = {};

    function buildError(text) {
        var error = new Error();
        text = text.replace(/^error:/, '');
        error.message = text;
        return error;
    }

    function checkPrivileges(response) {
        if (response && response.indexOf('no-rights') !== -1) {
            return true;
        }
        return false;
    }

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

    function ajaxFailHandler(xhr, callback) {
        var text = xhr.responseText;
        if (checkPrivileges(text)) {
            callback(buildSessionError());
            return true;
        } else {
            callback(buildError(text));
        }
    }

    provider.backToAdmin = function () {
        var currentUrl = context.location.href,
            index = currentUrl.lastIndexOf('&editor=1'),
            url = currentUrl.substr(0, index);
        context.location.replace(url);
    };

    provider.doExport = function (data, callback) {
        var request = {
            'save': {
                'post': {
                    data: JSON.stringify(data),
                    action: 'doExport',
                    template : config.infoData.themeName
                },
                'url': config.index
            },
            'clear': {
                'post': { action: 'clearChunks' },
                'url': config.index
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };

    provider.convertHtmlToCms = function convertHtmlToCms(fso, controlName) {
        if (!fso.exists('page.html')) return fso;

        var pageContent = fso.read('page.html');
        if (-1 == pageContent.indexOf('renderTemplateFromIncludes') && '' !== pageContent) {
            var name = controlName.constructorName.toLowerCase() + "_" + controlName.id,
                call = "<?php include($GLOBALS['designer_settings']['current_theme_path'] . '/includes/" + name + ".php'); ?>";
            fso.write('page.html', call);
            fso.write('includes/' + name + '.php', pageContent);
        }
        return fso;
    };

    provider.save = function (saveData, callback) {
        var request = {
            'save': {
                'post': {
                    data: JSON.stringify(saveData),
                    action: 'saveProject',
                    template : config.infoData.themeName
                },
                'url': config.index
            },
            'clear': {
                'post': { action: 'clearChunks' },
                'url': config.index
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };

    provider.updatePreviewTheme = function (callback) {
        $.ajax({
            type: "post",
            url: config.index,
            dataType: "json",
            data: {
                action      : 'updatePreview',
                template : config.infoData.themeName
            },
            success: function() {
                callback();
            },
            error: function(xhr, options, error) {
                ajaxFailHandler(xhr);
            }
        });
    };

    provider.getTheme = function (themeName, callback) {
        $.ajax({
            type: "post",
            url: config.index,
            dataType: "json",
            data: {
                action: 'getTheme',
                template: config.infoData.themeName,
                resultType: 'content',
                themeName: themeName || config.infoData.themeName
            },
            success: function (data) {
                callback(null, data);
            },
            error: function (xhr, options, error) {
                ajaxFailHandler(xhr);
            }
        });
    };

    provider.rename = function (themeName, callback) {
        $.ajax({
            type: "post",
            url: config.index,
            dataType: "json",
            data: {
                action: 'renameTheme',
                templateId: config.templateId,
                oldThemeName: config.infoData.themeName,
                newThemeName: themeName || config.infoData.themeName
            },
            success: function (data) {
                context.location.reload();
                //callback(null, data);
            },
            error: function (xhr, options, error) {
                ajaxFailHandler(xhr)
            }
        });
    }

    provider.load = function () {
        return config.projectData || {};
    };

    provider.getAllCssJsSources = function () {
        return config.cssJsSources;
    };

    provider.getMd5Hashes = function () {
        return config.md5Hashes;
    };

    provider.getThemeVersion   = function () {
        return config.revision;
    };

    provider.makeThemeAsActive = function (callback) {
        $.ajax({
            type: "post",
            url: config.index,
            dataType: "json",
            data: {
                action: 'makeThemeAsActive',
                templateId: config.templateId
            },
            success: function () {
                callback();
            },
            error: function(xhr, options, error) {
                ajaxFailHandler(xhr);
            }
        });
    };

    provider.getInfo = function() {
        config.infoData.cmsName = 'Joomla';
        config.infoData.thumbnails = [{name: 'template_preview.png', width: 800, height: 600},
            {name: 'template_thumbnail.png', width: 206, height: 150}]
        return config.infoData;
    };

    return provider;
}());