/*global ajaxurl, templateInfo, DataProviderHelper, SessionTimeoutError */

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

    function isInvalidFormKey(response) {
        response = response.message || response.content || response;
        return response === 'session_error' || response == -1;
    }

    function getSessionError() {
        var error = new SessionTimeoutError();
        error.loginUrl = templateInfo.login_page;
        return error;
    }

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

    DataProvider.doExport = function doExport(exportData, callback) {
        var request = {
            'save': {
                'post': {
                    data: JSON.stringify(exportData),
                    action: "theme_template_export",
                    uid: templateInfo.user,
                    _ajax_nonce: templateInfo.nonce
                },
                'url': ajaxurl
            },
            'clear': {
                'post': {
                    action: "theme_template_clear",
                    uid: templateInfo.user,
                    _ajax_nonce: templateInfo.nonce
                },
                'url': ajaxurl
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };
    DataProvider.getTheme = function getTheme(themeName, callback) {
        if (!callback || typeof callback !== 'function') {
            throw DataProviderHelper.getResultError('Invalid callback');
        }

        themeName = (themeName || '' !== themeName) ? themeName : templateInfo.base_template_name;

        window.jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: ({
                action: 'theme_get_theme',
                isUrl: false,
                themeName: themeName,
                uid: templateInfo.user,
                _ajax_nonce: templateInfo.nonce
            })
        }).done(function (data) {
                if (isInvalidFormKey(data)) {
                    callback(getSessionError());
                } else if (data) {
                    callback(null, data);
                } else {
                    callback(new Error('getTheme() server error: ' + data));
                }
            }).fail(function (xhr) {
                ajaxFailHandler(xhr, callback);
            });

    };
    DataProvider.updatePreviewTheme = function updatePreviewTheme(callback) {
        if (!callback || typeof callback !== 'function') {
            throw DataProviderHelper.getResultError('Invalid callback');
        }
        window.jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: ({
                action: 'theme_update_preview',
                uid: templateInfo.user,
                _ajax_nonce: templateInfo.nonce
            })
        }).done(function(data) {
                if (isInvalidFormKey(data)) {
                    callback(getSessionError());
                } else if ('1' === data) {
                    callback(null);
                } else {
                    callback(new Error('updatePreview() server error: ' + data));
                }
            }).fail(function (xhr) {
                ajaxFailHandler(xhr, callback);
            });
    };
    DataProvider.load = function () {
        return templateInfo.projectData;
    };
    DataProvider.save = function save(saveData, callback) {
        var request = {
            'save': {
                'post': {
                    data: JSON.stringify(saveData),
                    action: "theme_save_project",
                    uid: templateInfo.user,
                    _ajax_nonce: templateInfo.nonce
                },
                'url': ajaxurl
            },
            'clear': {
                'post': {
                    action: "theme_template_clear",
                    uid: templateInfo.user,
                    _ajax_nonce: templateInfo.nonce
                },
                'url': ajaxurl
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };
    DataProvider.rename = function rename(themeName, callback) {
        if (!callback || typeof callback !== 'function') {
            throw DataProviderHelper.getResultError('Invalid callback');
        }

        window.jQuery.ajax({
            url: ajaxurl,
            type: 'POST',
            data: ({
                action: 'theme_rename',
                themeName: themeName,
                uid: templateInfo.user,
                _ajax_nonce: templateInfo.nonce
            })
        }).done(function(data) {
                if (isInvalidFormKey(data)) {
                    callback(getSessionError());
                } else if('1' === data) {
                    callback(null);
                    window.location = window.location.href;
                } else {
                    callback(new Error('rename() server error: ' + data));
                }
            }).fail(function (xhr) {
                ajaxFailHandler(xhr, callback);
            });
    };
    DataProvider.backToAdmin = function backToAdmin() {
        // выкидывает на базовую страницу backend-а
        window.top.location = templateInfo.admin_url;
    };
    DataProvider.getAllCssJsSources = function getAllCssJsSources() {
        return templateInfo.cssJsSources;
    };
    DataProvider.getMd5Hashes = function getMd5Hashes() {
        return templateInfo.md5Hashes;
    };
    DataProvider.convertHtmlToCms = function convertHtmlToCms(fso, control) {
        if (fso.exists('page.html')) {
            var control_view = fso.read('page.html');
            if ($.trim(control_view) === '') {
                return fso;
            }
            if (false === /<\?php/.test(control_view)) {
                var control_name = control.constructorName.toLowerCase() + '_' + control.id;
                fso.write('page.html', "<?php include( STYLESHEETPATH . '/templates/" + control_name + ".php'); ?>");
                fso.write('templates/' + control_name + '.php', control_view);
            }
        }
        return fso;
    };
    DataProvider.getInfo = function getInfo(){
        var previewUrl = 'preview=1&template=' + templateInfo.template_name + '&stylesheet=' + templateInfo.template_name + '&preview_iframe=1&TB_iframe=true';
        var templates = {};

        templates.home = templateInfo.home_url + '/?' + previewUrl;
        templates.default = templateInfo.home_url + '/?s=test&' + previewUrl;
        if (templateInfo.woocommerce_enabled) {
            templates.products = templateInfo.home_url + '/?post_type=product&' + previewUrl;
            templates.productOverview = templateInfo.home_url + '/?' + templateInfo.templates.product_url + previewUrl;
            templates.shoppingCartTemplate = templateInfo.home_url + '/?' + templateInfo.templates.cart_url + previewUrl;
        }
        if (templateInfo.templates.blogpage_url){
            templates.blogTemplate = templateInfo.home_url + '/?' + templateInfo.templates.blogpage_url + previewUrl;
        } else {
            templates.blogTemplate = templateInfo.home_url + '/wp-content/themes/' + templateInfo.template_name + '/no-blog-template.php';
        }
        templates.singlePostTemplate = templateInfo.home_url + '/?' + templateInfo.templates.singlepost_url + previewUrl;
        templates.pageTemplate = templateInfo.home_url + '/?' + templateInfo.templates.page_url + previewUrl;
        templates.template404 = templateInfo.home_url + '/?page_id=1234567&' + previewUrl;

        var infoData = {};
        infoData.cmsName    = 'WordPress';
        infoData.cmsVersion = templateInfo.cms_version;
        infoData.adminPage  = templateInfo.home_url + '/wp-admin/themes.php';
        infoData.startPage  = templateInfo.home_url + '/?' + previewUrl;
        infoData.templates  = templates;
        infoData.thumbnails = [{name: "screenshot.png", width: 600, height: 450}];
        infoData.isThemeActive = true;
        infoData.themeName = templateInfo.base_template_name;

        return infoData;
    };
})();