{% load i18n %}

var OfficePreviewer = function(repo_id, path, token, commit_id) {
    this.repo_id = repo_id;
    this.path = path;
    this.total_pages = null;
    // only non-null when viewing in shared links
    this.token = token;
    this.commit_id = commit_id;

    this.orig_page_width = null;
    this.orig_page_height = null;

    this.server_processed_pages = 0;
    this.current_loading_page = 1;
    this.iframes = [];

    this.FIT_TO_WIDTH = 850;    // hardcoded in seafevents
    this.scale_ratio = 1;
    this.static_prefix = '{{ SITE_ROOT}}office-convert/static/{{ repo.id }}/' + this.commit_id + '{{ path|urlencode }}/';

    this.page_status_url = function(page) {
        var params = {
            repo_id: repo_id,
            commit_id: this.commit_id,
            path: path,
            page: page
        };
        if (this.token) {
            params['token'] = this.token;
        }
        return "{% url 'office_convert_query_status' %}?" + $.param(params);
    }
    this.page_content_url = function(page) {
        var url = this.static_prefix + page + '.page';
        var params = {};
        if (this.token) {
            params['token'] = token;
        }
        return params ? url + '?' + $.param(params) : url;
    }

    var url = window.location.href;
    var arr = url.split("/");
    // need the current domain to post message to iframe (for zoom in/out)
    this.origin = arr[0] + "//" + arr[2];
};

OfficePreviewer.prototype.start = function() {
    this.check_page_status();
    return this;
};

OfficePreviewer.prototype.check_page_status = function() {
    var page = this.current_loading_page;
    if (this.server_processed_pages >= page) {
        this.load_page(page);
        return;
    }
    $.ajax({
        context: this,
        url: this.page_status_url(page),
        cache: false,
        dataType: 'json',
        success: function(data) {
            var status = data['status'];
            switch (status) {
            case 'PROCESSING':
                setTimeout($.proxy(this.check_page_status, this), 2000);
                break;
            case 'ERROR':
                if (page == 1) {
                    var str = "{% trans "Document convertion failed." %}";
                    $('#file-view').html('<div id="file-view-tip"><p class="error">' + str + '</p></div>');
                } else {
                    $('.page-container:last').clone().css({'background':'#fff'}).html('<p class="error alc" style="margin-top:6em;">' + "{% trans "Failed to load this page." %}" + '</p>').appendTo($('#pages'));
                    $('#file-view .loading-tip').hide();
                }
                break;
            case 'DONE':
                var info = data['info'];
                if (info) {
                  this.total_pages = info['final_pages'];
                  this.server_processed_pages = info['processed_pages'];
                  this.orig_page_width = info['page_width'];
                  this.orig_page_height = info['page_height'];
                }
                this.load_page(page);
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            var str;
            if (xhr.responseText) {
                str = "{% trans "Document convertion failed." %}";
            } else {
                str = "{% trans "Failed. Please check the network." %}";
            }
            if (page == 1) {
                $('#file-view').html('<div id="file-view-tip"><p class="error">' + str + '</p></div>');
            } else {
                $('.page-container:last').clone().css({'background':'#fff'}).html('<p class="error alc" style="margin-top:6em;">' + str + '</p>').appendTo($('#pages'));
                $('#file-view .loading-tip').hide();
            }
        }
    });
};

OfficePreviewer.prototype.add_toolbar = function() {
    var $toolbar = $('<div id="pdf2html-toolbar-2" class="pdf2html-toolbar"></div>')
        .append('<div class="inner"><span class="icon-zoom-out" id="zoom-out"></span><span class="icon-zoom-in" id="zoom-in"></span></div>')
        .appendTo($('#file-view'));
    $toolbar.css({'left': $(window).width()/2 - $toolbar.outerWidth(true)/2});

    setTimeout(function () { $toolbar.css({'opacity':0}); }, 4000);
    $toolbar.hover(
        function() { $(this).css({'opacity': 1}); },
        function() { $(this).css({'opacity': 0}); }
    );

    var scale_ratio_offset = 0.1;
    $('#zoom-in, #zoom-out').click($.proxy(function(event) {
        // zoom in/out
        var scale_ratio = this.scale_ratio;
        var op = event.target.id;
        if (op == 'zoom-in') {
            scale_ratio += scale_ratio_offset;
        } else {
            scale_ratio -= scale_ratio_offset;
        }

        if (scale_ratio <= 0) {
            return ;
        }
        this.scale_ratio = scale_ratio;

        var self = this;
        $(this.iframes).each(function(index, iframe) {
            self.scale_iframe(iframe);
        });

        this.set_page_container_size();

    }, this));
}

OfficePreviewer.prototype.scale_iframe = function(iframe) {
    iframe.contentWindow.postMessage({scale: this.scale_ratio}, this.origin);
}

OfficePreviewer.prototype.set_page_container_size = function(elt) {
    // orig_page_height / h = orig_page_width / this.FIT_TO_WIDTH
    elt = elt || $('.page-container');
    var h = this.orig_page_height * this.FIT_TO_WIDTH / this.orig_page_width;
    elt.css({
        width: this.FIT_TO_WIDTH * this.scale_ratio,
        height: h * this.scale_ratio
    });
}

OfficePreviewer.prototype.load_page = function(index) {
    var $pagesContainer = $('#pages');
    if (index == 1) {
        this.add_toolbar();
        $('#file-view').css({'height': 'auto'});
        $pagesContainer.removeClass('hide');
    }

    var page_container = $('<div class="page-container"></div>');
    this.set_page_container_size(page_container);
    $pagesContainer.append(page_container);

    var iframe = $('<iframe src="' + this.page_content_url(index) + '" />');
    page_container.append(iframe);

    this.iframes.push(iframe[0]);
    var self = this;
    iframe.load(function() {
        // set proper scale factor when iframe is loaded
        if (self.scale_ratio != 1) {
            self.scale_iframe(this);
        }
    });

    if (index < this.total_pages) {
        this.current_loading_page++;
        this.check_page_status();
    } else {
        $('#file-view .loading-tip').hide();
    }
};

$(function() {
    var commit_id = '{{ current_commit.id }}' || '{{ repo.head_cmmt_id }}';
    new OfficePreviewer('{{ repo.id }}', '{{ path }}', '{{ shared_token }}', commit_id).start();
});
