/*global $, DataProviderHelper, SessionTimeoutError, LayoutContainer */
//@*--
var DataProvider = {};
(function () {
    'use strict';

    function isInvalidFormKey(response) {
        response = response.message || response.content || response;
        return typeof response === 'string' &&
            (response.indexOf('refresh the page') !== -1 || response.indexOf('body id="page-login"') !== -1);

    }

    function getSessionError() {
        var error = new SessionTimeoutError();
        error.loginUrl = window.themeDesigner.url.designer;
        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.load = function load() {
        return window.themeDesigner.theme.projectData.projectData;
    };

    DataProvider.save = function save(saveData, callback) {
        var request = {
            'save': {
                'post': {
                    data: JSON.stringify(saveData),
                    form_key: window.themeDesigner.ajaxUrl.key
                },
                'url': window.themeDesigner.ajaxUrl.cmsExport
            },
            'clear': {
                'post': {
                    form_key: window.themeDesigner.ajaxUrl.key
                },
                'url': window.themeDesigner.ajaxUrl.clear
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };

    DataProvider.doExport = function doExport(data, callback) {
        var request = {
            'save': {
                'post': {
                    data: JSON.stringify(data),
                    form_key: window.themeDesigner.ajaxUrl.key,
                    debug : typeof window.debug !== 'undefined'
                },
                'url': window.themeDesigner.ajaxUrl.cmsExport
            },
            'clear': {
                'post': {
                    form_key: window.themeDesigner.ajaxUrl.key
                },
                'url': window.themeDesigner.ajaxUrl.clear
            },
            'errorHandler': ajaxFailHandler
        };
        DataProviderHelper.saveChunks(request, callback);
    };

    DataProvider.convertHtmlToCms = function convertHtmlToCms(fso, control) {
        var controlName = control.constructorName.toLowerCase();
        var callParams = [
            "'converted/" + controlName + "'",
            control.id
        ];
        if (fso.exists('page.html')) {
            var controlView = $.trim(fso.read('page.html'));
            if (controlView && /^<\?php[\s\S]+\?>$/.test($.trim(controlView)) === false) {
                var controlCall;
                if (control instanceof LayoutContainer) {
                    controlCall = "<?php include Mage::getSingleton('core/design_package')->getBaseDir(array('_type' => 'template', '_default' => false)) . '/designer/converted/" + controlName + '_' + control.id + ".phtml' ?>";
                } else {
                    controlCall = "<?php echo Mage::helper('designer')->createTemplate(" + callParams.join(', ') + ")->setContext($this)->toHtml() ?>";
                }
                fso.write('page.html', controlCall);
                fso.write('includes/converted/' + controlName + '_' + control.id + '.phtml', controlView);
            }
        }
        return fso;
    };

    DataProvider.getMd5Hashes = function getMd5Hashes() {
        return window.themeDesigner.theme.hashes;
    };

    DataProvider.getAllCssJsSources = function getAllCssJsSources() {
        return window.themeDesigner.theme.cache;
    };

    DataProvider.updatePreviewTheme = function updatePreviewTheme(callback) {
        $.ajax({
            type: 'get',
            url: window.themeDesigner.ajaxUrl.updatePreview
        })
        .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: 'get',
            url: window.themeDesigner.ajaxUrl.publish,
            data: {
                form_key: window.themeDesigner.ajaxUrl.key
            }
        }).done(function (response) {
            var error = null;
            if (isInvalidFormKey(response)) {
                error = getSessionError();
            } else {
                window.themeDesigner.theme.active = true;
            }
            callback(error);
        }).fail(function (xhr) {
            ajaxFailHandler(xhr, callback);
        });
    };

    DataProvider.getTheme = function getTheme(themeName, callback) {
        $.ajax({
            type: 'get',
            url: window.themeDesigner.ajaxUrl.download,
            dataType: 'json',
            data: {
                form_key: window.themeDesigner.ajaxUrl.key,
                themeName: 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.backToAdmin = function backToAdmin() {
        window.location = window.themeDesigner.url.admin;
    };

    DataProvider.getInfo = function getInfo() {
        return {
            cmsName: 'Magento',
            cmsVersion: JSON.parse(window.themeDesigner.settings.cmsVersion),
            adminPage: window.themeDesigner.url.admin,
            startPage: window.themeDesigner.url.preview,
            templates: window.themeDesigner.templates,
            thumbnails: [{name: 'preview.png', width: 100, height: 100}],
            isThemeActive: window.themeDesigner.theme.active,
            themeName: window.themeDesigner.theme.name
        };
    };

    DataProvider.rename = function rename(themeName, callback) {
        $.ajax({
            type: 'post',
            url: window.themeDesigner.ajaxUrl.rename,
            dataType: 'json',
            data: {
                form_key: window.themeDesigner.ajaxUrl.key,
                newName: 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 === 'OK') {
                    callback(null);
                    window.location = window.location.toString().replace(new RegExp('theme=' + window.themeDesigner.theme.name), 'theme=' + themeName);
                } 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);
        });
    };

}());

//--*@