/*global DataUploader, upageEditor */

window.upageEditor = {};

(function() {
    'use strict';

    function addEvent(elem, name, handler) {
        if (elem.addEventListener){
            elem.addEventListener(name, handler, false);
        } else {
            elem.attachEvent(name, handler);
        }
    }

    document.addEventListener("DOMContentLoaded", function() {
        addEvent(document.body, 'upageClose', upageEditor.close);
    });
})();

window.upageEditor.uploads = {};
window.upageEditor.idsMap = {};

window.upageEditor.uploadSections = function uploadSections(allHtml, callback) {
    'use strict';

    uploadImages(allHtml, function(allHtml) {
        var doms = $(allHtml);
        var updateData = [];
        var sections = [];

        doms.each(function(i, el) {
            var sectionDom = $(el);
            if (sectionDom.is('style')) {
                return;
            }

            var styleDom = sectionDom.prev();
            var html = styleDom[0].outerHTML + '\n' + sectionDom[0].outerHTML;

            sections.push({
                html: html,
                styleDom: styleDom,
                sectionDom: sectionDom,
                dataId: sectionDom.attr('data-id'),
                thumbnailUrl: sectionDom.attr('data-thumbnail')
            });
        });

        sections.forEach(function(section) {
            var html = section.html
                .replace(/data-thumbnail="[^"]*"/g, '')
                .replace(/data-media-id="[^"]*"/g, '');

            var mediaId = section.sectionDom.attr('data-media-id') || upageEditor.idsMap[section.dataId] || 0;

            updateData.push({
                html: html,
                mediaId: mediaId,
                thumbnail: upageEditor.uploads[section.thumbnailUrl]
            });
        });

        DataUploader.uploadSections(updateData, function (error, response) {
            if (error) {
                callback(error);
                return;
            }
            for (var i = 0; i < sections.length; i++) {
                var section = sections[i],
                    changes = response.data[i];
                section.mediaId = changes.section_id;
                upageEditor.idsMap[section.dataId] = section.mediaId;
            }
            callback(null, sections);
        });
    });

    function uploadImages(html, callback) {
        var uploadRequired = {};

        html.replace(/"(data:[^"]*?;base64,[^"]*)"/g, function(match, dataUrl) {
            uploadRequired[dataUrl] = upageEditor.uploads[dataUrl];
            return '';
        }).replace(/(https?:)?\/\/(\S+?)\.(png|jpg|gif|svg|ico|jpeg|bmp)(\?[^"\)\s]*|)/gi, function(url) {
            if (url.indexOf(location.protocol + '//' + location.host) !== 0) {
                uploadRequired[url] = upageEditor.uploads[url];
            }
            return '';
        });

        DataUploader.uploadImages(uploadRequired, function() {
            for(var url in uploadRequired) {
                if (uploadRequired.hasOwnProperty(url) && uploadRequired[url]) {
                    var newUrl = uploadRequired[url].url;
                    html = html.split(url).join(newUrl);

                    upageEditor.uploads[url] = uploadRequired[url];
                    upageEditor.uploads[newUrl] = uploadRequired[url];
                }
            }
            callback(html);
        });
    }
};

window.upageEditor.updatePageSections = function uploadSections(pageId, sections, callback) {
    'use strict';

    var allHtml = '';
    sections.forEach(function(section) {
        if (section.html) {
            var doms = $(section.html);
            doms.filter(':not(style)').attr('data-thumbnail', section.thumbnailUrl);
            allHtml += $('<div>').append(doms).html();
        }
    });

    upageEditor.uploadSections(allHtml, function(error, result) {
        if (error) {
            callback(error);
            return;
        }
        DataUploader.getPage(pageId, function(error, response) {
            if (error) {
                callback(error);
                return;
            }

            var map = {};
            // old
            response.data.items.forEach(function(item) {
                map[item.clientId] = item.id;
            });

            // new
            result.forEach(function(item) {
                map[item.dataId] = item.mediaId;
            });

            var shortcode = '';
            sections.forEach(function(item) {
                shortcode += '[upage_section id=' + map[item.clientId] + ']\n';
            });

            DataUploader.updatePost({
                id: pageId,
                content: shortcode
            }, function(error) {
                callback(error);
            });

        });
    });
};

window.upageEditor.save = function save(saveData, onComplete) {
    'use strict';

    var callback = function(error, hasChanges) {
        upageEditor.hasChanges = !!upageEditor.hasChanges || hasChanges;
        onComplete(error);
    }.bind(this);

    var sections = $(saveData.html).filter('[data-id]');

    var allHtml = '';
    sections.each(function(i, section) {
        allHtml += section.outerHTML;
    });

    upageEditor.uploadSections(allHtml, function(error, sections) {
        var shortcode = '';

        sections.forEach(function(section) {
            shortcode += '[upage_section id=' + section.mediaId + ']\n';
        });

        DataUploader.updatePost({
            id: saveData.id,
            content: shortcode
        }, function() {
            callback(null, true);
        });
    });
};

window.upageEditor.saveThumbnail = function saveThumbnail(saveData, callback) {
    'use strict';

    var uploadRequired = {};

    saveData.forEach(function (sectionInfo) {
        uploadRequired[sectionInfo.thumbnailUrl] = upageEditor.uploads[sectionInfo.thumbnailUrl];
    });

    DataUploader.uploadImages(uploadRequired, function() {

        var updateData = [];

        saveData.forEach(function (sectionInfo) {

            var mediaId = upageEditor.idsMap[sectionInfo.clientId];

            if (mediaId) {
                var uploadResult = uploadRequired[sectionInfo.thumbnailUrl];
                if (uploadResult) {
                    updateData.push({
                        mediaId: mediaId,
                        thumbnail: uploadResult
                    });
                }
            }
        });

        DataUploader.uploadSections(updateData, function (error) {
            callback(error);
        });
    });

};

window.upageEditor.close = function save() {
    'use strict';

    var win = window.parent || window;

    win.postMessage(JSON.stringify({
        message: 'savingEnd',
        hasChanges: upageEditor.hasChanges
    }), location.origin);
};