{% extends "home_base.html" %}

{% load seahub_tags avatar_tags i18n staticfiles %}

{% block sub_title %}{% trans "Wikis" %} - {% endblock %}

{% block cur_personal_wiki %}tab-cur{% endblock %}

{% block right_panel %}
    <div class="hd d-flex">
        <h3>{% trans "Wikis" %}</h3>
        <div class="add-wiki-container">
        </div>
    </div>
    <span class="loading-icon loading-tip"></span>
    <table class="wiki-list hide user-select-no">
        <thead>
        <tr>
            <td width="50%">{% trans "Name" %}</td>
            <td width="20%">{% trans "Owner" %}</td>
            <td width="20%">{% trans "Last Update" %}</td>
            <td width="10%"><!-- operation --></td>
        </tr>
        </thead>
        <tbody></tbody>
    </table>
    <div class="empty-tips hide">
        <h2 class="alc">{% trans "You do not have any wiki" %}</h2>
        <p>{% trans "Seafile Wiki enables you to organize your knowledge in a simple way. The contents of wiki is stored in a normal library with pre-defined file/folder structure. This enables you to edit your wiki in your desktop and then sync back to the server." %}</p>
    </div>
    <p class="error wiki-list-error hide"></p>

    <form id="new-wiki-form" action="" method="post" class="hide">{% csrf_token %}
        <h3 id="dialogTitle">{% trans "New Wiki" %}</h3>
        <label for="wiki-name">{% trans "Name" %}</label><br/>
        <input type="text" name="name" value="" maxlength="{{max_file_name}}" class="input" id="wiki-name" /><br />
        <p class="error hide"></p>
        <button type="submit" class="submit">{% trans "Submit" %}</button>
    </form>

    <form id="new-wiki-by-existing-form" action="" method="post" class="hide">{% csrf_token %}
        <h3 id="dialogTitle">{% trans "Create Wiki from a library" %}</h3>
        <span class="loading-icon loading-tip"></span>
        <div class="repo-container">
            <table class="repo-list">
                <thead>
                    <tr>
                        <th width="3%"><!--select--></th>
                        <th width="4%"><!--icon--></th>
                        <th width="38%">{% trans "Name" %}</th>
                        <th width="25%">{% trans "Last Update" %}</th>
                    </tr>
                </thead>
                <tbody></tbody>
            </table>
        </div>
        <p class="error hide"></p>
        <button type="submit" class="submit">{% trans "Submit" %}</button>
    </form>

    <script type="text/script" id="wiki-tmpl">
        <tr data-slug="<%= slug %>">
            <td>
                <span class="wiki-name">
                    <a href="<%= link %>"><%- name %></a>
                <span>
            </td>
            <td><a href="<%= owner_profile_url %>"><%- owner_nickname %></a></td>
            <td title="<%= update_time %>"><%= update_time_from_now %></td>
            <td class="wiki-op">
                <div class="sf-dropdown">
                    <a class="wiki-dropdown-toggle sf2-icon-more op-icon vh" title="{% trans "More Operations" %}" aria-label="{% trans "More Operations" %}"></a>
                    <ul class="sf-dropdown-menu wiki-dropdown-menu hide hidden-op">
                        <li><a class="rename-wiki op">{% trans "Rename" %}</a></li>
                        <li><a class="delete-wiki op">{% trans "Delete" %}</a></li>
                    </ul>
                </div>
            </td>
        </tr>
    </script>
<script type="text/template" id="wiki-rename-form-tmpl">
    <form id="rename-form" class="inline-rename-form" action="" method="post">
        <input type="text" name="newname" value="<%- wiki_name %>" class="input vam" maxlength="{{max_file_name}}" />
        <button type="submit" class="submit sf2-icon-tick tick-green vam" title="{% trans "Submit" %}"></button>
        <button type="button" class="cancel sf2-icon-x2 vam" title="{% trans "Cancel" %}"></button>
    </form>
</script>
<script type="text/template" id="wiki-add-wiki-tmpl">
<button class="btn-white sf-dropdown-toggle hidden-sm-down add-wiki"><span aria-hidden="true" class="icon-plus-square add vam"></span><span class="vam">{% trans "Add Wiki"%}</span></button>
<span aria-label="{% trans "Add Wiki" %}" class="hidden-md-up sf-dropdown-toggle sf2-icon-plus2 mobile-icon"></span>
<ul class="sf-dropdown-menu wiki-dropdown-menu hide">
    <li><a class="op new-wiki-by-build" href="#">{% trans "New Wiki" %}</a></li>
    <li><a class="op new-wiki-by-own" href="#">{% trans "Choose a library as Wiki" %}</a></li>
</ul>
</script>
<script type="text/template" id="wiki-choose-wiki-tmpl">
<% var repos = obj %>
<% for (var i = 0; i< repos.length; i++) {%>
    <% var repo = repos[i] %>
    <tr>
        <td><input type="radio" name="repo" class="vam" value="<%= repo.id%>"/></td>
        <td>
        <% if (repo.encrypted) { %>
        <img src="{{ MEDIA_URL }}img/lib/48/lib-encrypted.png" width="24" />
        <% } else { %>
        <img src="{{ MEDIA_URL }}img/lib/48/lib.png" width="24" />
        <% } %>
        </td>
        <td class="repo-name"><%= repo.name %></td>
        <td><%= repo.mtime_relative %></td>
    </tr>
<% }%>
</script>
{% endblock %}

{% block extra_script %}{{block.super}}
<script type="text/javascript" src="{% static "scripts/lib/underscore.js" %}"></script>
<script type="text/javascript" src="{% static "scripts/lib/moment-with-locales.min.js" %}"></script>
<script type="text/javascript">
// get wiki list
$.ajax({
    url: '{% url 'api-v2.1-wikis' %}',
    cache: false,
    dataType: 'json',
    success: function(data) {
        var list = data.data;
        var $tbody = $('.wiki-list tbody');
        if (list.length) {
            $(list).each(function(index, item) {
                $tbody.append(wiki.render(item));
            });
            $('table').show();
        } else {
            $('.empty-tips').show();
        }
    },
    error: function(xhr) {
        var error_msg;
        if (xhr.responseText) {
            try {
                error_msg = JSON.parse(xhr.responseText).error_msg;
            } catch(e) {
                error_msg = "{% trans "Error" %}";
            }
        } else {
            error_msg = "{% trans "Please check the network." %}";
        }
        $('.wiki-list-error').html(error_msg).show();
    },
    complete: function() {
        $('#right-panel .loading-tip').hide();
    }
});

var wiki = {

    init: function() {
        this.setLocale();
    },

    tmpl: _.template($('#wiki-tmpl').html()),

    render: function(obj) {

        var update_time, update_time_from_now;
        if (obj.updated_at) {
            var update_at_m = moment(obj.updated_at);
            update_time = update_at_m.format('LLLL');
            update_time_from_now = this.util_getRelativeTimeStr(update_at_m);
        } else { // sth. wrong with updated_at, and it returns `''`.
            update_time = '--';
            update_time_from_now = '--';
        }

        var data = $.extend({}, obj, {
            'owner_profile_url': '{{SITE_ROOT}}profile/' + encodeURIComponent(obj.owner) + '/',
            'update_time': update_time,
            'update_time_from_now': update_time_from_now
        });

        return $(this.tmpl(data));
    },

    del: function(options) {
        var slug = options.slug,
            $el = options.$el;
        $.ajax({
            url: '{{SITE_ROOT}}api/v2.1/wikis/' + encodeURIComponent(slug) + '/',
            type: 'DELETE',
            cache: false,
            beforeSend: prepareCSRFToken,
            success: function(data) {
                $el.remove();
                feedback("{% trans "Successfully deleted 1 item." %}", 'success');
            },
            error: function(xhr) {
                var error_msg;
                if (xhr.responseText) {
                    try {
                        error_msg = JSON.parse(xhr.responseText).error_msg;
                    } catch(e) {
                        error_msg = "{% trans "Error" %}";
                    }
                } else {
                    error_msg = "{% trans "Please check the network." %}";
                }
                feedback(error_msg, 'error');
            }
        });
    },

    setLocale: function() {
        var lang_code = '{{LANGUAGE_CODE}}';
        var m_lang_code;
        if (lang_code == 'en') {
            m_lang_code = 'en-gb';
        } else if (lang_code == 'es-ar' || lang_code == 'es-mx') {
            m_lang_code = 'es';
        } else {
            m_lang_code = lang_code;
        }
        moment.locale(m_lang_code);
    },

    util_getRelativeTimeStr: function(m) {
        var now = new Date();
        if (m - now > 0) {
            return "{% trans "Just now" %}";
        } else {
            return m.fromNow();
        }
    }
};
wiki.init();

var wikiListController = {

    $wikiList: $('.wiki-list'),

    renameTemplate : _.template($('#wiki-rename-form-tmpl').html()),

    init: function() {
        //init dom event
        var _this = this;
        var $wikiList = this.$wikiList;
        $wikiList.on('click', '.wiki-dropdown-toggle', $.proxy(_this.showWikiMenu, _this));
        $wikiList.on('click', '.delete-wiki', $.proxy(_this.deleteCurrentWiki, _this));
        $wikiList.on('click', '.rename-wiki', $.proxy(_this.showRenameTmpl, _this));

        //handle menu event;
        $(document).on('click', function(event){
            var view = _this.$wikiMenu;
            var target = event.target || event.srcElement;

            if (!view) {
                return true;
            }
            if (!view.is(target) &&
                !view.find('*').is(target)) {
                _this.hideWikiMenu();
            }
            return true;
        })
    },

    showOwnerInfo: function(){},

    showWikiMenu: function(event) {
        var target = event.target || event.srcElement;
        var $wikiMenu = $(target).parent().find('.sf-dropdown-menu');
        var $tr = $(target).closest('tr');
        if (this.$wikiMenu) {
            if ($wikiMenu.length && $wikiMenu.is(this.$wikiMenu)) {
                app.ui.currentDropDown = false;
                this.$wikiMenu.addClass('hide');
                this.$wikiMenu = null;
                return false;
            }else{
                this.hideWikiMenu();
            }
        }
        this.$wikiMenu = $wikiMenu;
        app.ui.currentDropDown = true;
        this.$wikiMenu.removeClass('hide');
        return false;
    },

    hideWikiMenu: function() {
        app.ui.currentDropDown = false;
        this.$wikiMenu.addClass('hide');
        this.$wikiMenu.closest('tr').removeClass('hl').find('.op-icon, .op').addClass('vh'); 
        this.$wikiMenu = null;
    },

    deleteCurrentWiki: function(event) {
        this.hideWikiMenu();
        var target = event.target || event.srcElement;
        var $el = $(target).closest('tr');
        var slug = $el.attr('data-slug');
        var title = "{% trans "Delete Wiki" %}",
            content = "{% trans "Are you sure you want to delete this wiki?" %}";
        var yesCallback = function(e) {
            wiki.del({
                $el: $el,
                slug: slug
            });
            $.modal.close();
        };
        showConfirm(title, content, yesCallback);
        return false;
    },

    showRenameTmpl: function(event) {
        var target = event.target || event.srcElement;
        var $tr = $(target).closest('tr');
        var slug = $tr.attr('data-slug');
        var wikiName = $tr.find('.wiki-name a').text();

        var form = $(this.renameTemplate({
            wiki_name: wikiName
        }));

        var $name = $tr.find('.wiki-name');
        var $op   = $tr.find('wiki-op');

        var $td   = $name.closest('td');
        $td.attr('colsepan', 2).css({
            'width': $name.width() + $op.outerWidth(),
            'height': $name.height()
        }).append(form);

        $op.hide();
        $name.hide();

        var $input = $('[name="newname"]', form);
        var dot_index = wikiName.lastIndexOf('.');
        if (dot_index != -1) {
            $input.trigger('focus');
            $input[0].setSelectionRange(0, dot_index);
        } else {
            $input.trigger('select');
        }

        //todos op select event

        var cancelRename = function() {
            app.ui.freezeItemHightlight = false;
            form.remove();
            $op.show();
            $name.show();
            $td.attr('colspan', 1).css({
                'width': $name.width()
            })

            return false;
        }

        var after_op_success = function(data) {
            app.ui.freezeItemHightlight = false;
            $tr.attr('data-slug', data.slug)
            $tr.find('.wiki-name a').text(data.name);
            $tr.find('.wiki-name a').attr('href', data.link);
            cancelRename();
        }

        $('.cancel', form).on('click', cancelRename);

        form.on('submit', function() {
            var new_name = $.trim($('[name=newname]', form).val());
            var err_msg;

            if(!new_name){
                err_msg = "{% trans "It is required." %}";
                feedback(err_msg, 'error');
                return false;
            }

            if (new_name.indexOf('/') != -1) {
                err_msg = "{% trans "Name should not include '/'." %}";
                feedback(err_msg, 'error');
                return false;
            }

            if (new_name == wikiName) {
                cancelRename();
                return false;
            }

            var submit_btn = $('[type="submit"]', form);
            disable(submit_btn);

            var after_op_error = function(xhr) {
                var err_msg;
                if (xhr.responseText) {
                    err_msg = JSON.parse(xhr.responseText).error_msg;
                } else {
                    err_msg =  "{% trans "Failed. Please check the network." %}";
                }
                feedback(err_msg, 'error');
                enable(submit_btn);
            };
            //call ajax  rename the model info
            var post_data = {"wiki_name" : new_name};
            $.ajax({
                url: '{{SITE_ROOT}}api/v2.1/wikis/' + encodeURIComponent(slug) + '/',
                type: 'POST',
                dataType: 'json',
                beforeSend: prepareCSRFToken,
                data: post_data,
                success: function(data) {
                    after_op_success(data);
                },
                err: function(xhr){
                    after_op_error(xhr);
                }
            })
            return false;
        })
        this.hideWikiMenu();
        app.ui.freezeItemHightlight = true;
        return false;
    },

}

wikiListController.init();

var NewWikiController = {
    el: $('.add-wiki-container'),
    chooseEl: $('#new-wiki-by-existing-form tbody'),

    addWikiTmpl: _.template($('#wiki-add-wiki-tmpl').html()),
    chooseWikiTmpl: _.template($('#wiki-choose-wiki-tmpl').html()),

    init: function() {
        var _this = this;
        this.el.append(this.addWikiTmpl);

        $('.add-wiki').on('click', $.proxy(_this.showWikiMenu, _this));

        $('.new-wiki-by-build').on('click', $.proxy(_this.clickToNewWiki, _this));
        $('.new-wiki-by-own').on('click', $.proxy(_this.clickToNewWikiByOwnlib, _this));

        $('#new-wiki-form').on('submit', $.proxy(_this.handlerDriectNewWikiEvent, _this));
        $('#new-wiki-by-existing-form').on('submit', $.proxy(_this.handlerDependentNewWikiEvent, _this));

        $(document).on("click", function(event) {
            var view = _this.newWikiMenu;
            var target = event.target || event.srcElement;

            if (!view) {
                return true;
            }
            if (!view.is(target) &&
                !view.find('*').is(target)) {
                _this.hideWikiMenu();
            }
            return true;
        });
    },

    clickToNewWiki: function() {
        $('#new-wiki-form').modal();
        $('#simplemodal-container').css({'width':'auto', 'height':'auto'})
    },

    clickToNewWikiByOwnlib: function(event) {
        var _this = this;
        $.ajax({
            url: "{{SITE_ROOT}}api2/repos/",
            cache: false,
            dataType: 'json',
            success: function(data) {
                var repos = data.filter(function(i) {
                    return i['encrypted'] !== true;
                    }        
                ) 
                
                var seenNames = {};

                var array = repos.filter(function(currentObject) {
                    if (currentObject.id in seenNames) {
                        return false;
                    } else {
                        seenNames[currentObject.id] = true;
                        return true;
                    }
                });

                if (array && array.length) {
                    _this.chooseEl.append($(_this.chooseWikiTmpl(array)));
                    $('#new-wiki-by-existing-form').modal();
                    $('#simplemodal-container').css({'width':'auto', 'height':'auto'})
                }
            },
            error: function(xhr) {
                var error_msg;
                if (xhr.responseText) {
                    try {
                        error_msg = JSON.parse(xhr.responseText).error_msg;
                    } catch(e) {
                        error_msg = "{% trans "Error" %}";
                    }
                } else {
                    error_msg = "{% trans "Please check the network." %}";
                }
                 _this.chooseEl.html(error_msg);
            },
            complete: function() {
                $('#new-wiki-by-existing-form .loading-tip').hide();
            }
        });
        },

    handlerDriectNewWikiEvent(event) {
        var $form = $(event.target);
        var name = $('[name="name"]', $form).val();
        var params = {
            use_exist_repo: false,
            repo_id: '',
            name: name
        }
        this.updateWikiList($form, params);
        
        return false;
    },

    handlerDependentNewWikiEvent: function(event) {
        var $form = $(event.target);
        var radio = $("input:radio:checked", $form);
        var repo_id = $("input:radio:checked", $form).val();
        var name = radio.closest('tr').find(".repo-name").text();
        var params = {
            use_exist_repo: true,
            repo_id: repo_id,
            name: name,
        }
        this.updateWikiList($form,params);
        return false;
    },

    updateWikiList: function($container, ajaxData){
        var $form = $container,
            $error = $('.error', $form);
        var $table = $('.wiki-list'),
            $tbody = $('tbody', $table),
            $emptyTips = $('.empty-tips');

        if (!$.trim(ajaxData.name)) {
            $error.html("{% trans "Name is required." %}").show();
            return false;
        }

        var $submitBtn = $('[type="submit"]', $form);
        disable($submitBtn);

        $.ajax({
            url: '{% url 'api-v2.1-wikis' %}',
            type: 'POST',
            dataType: 'json',
            cache: false,
            beforeSend: prepareCSRFToken,
            data: ajaxData,
            success: function(data) {
                $.modal.close();
                var $wiki = wiki.render(data);
                if ($emptyTips.is(':visible')) {
                    $tbody.append($wiki);
                    $emptyTips.hide();
                    $table.show();
                } else {
                    $tbody.prepend($wiki);
                }
            },
            error: function(xhr) {
                var error_msg;
                if (xhr.responseText) {
                    try {
                        error_msg = JSON.parse(xhr.responseText).error_msg;
                    } catch(e) {
                        error_msg = "{% trans "Error" %}";
                    }
                } else {
                    error_msg = "{% trans "Please check the network." %}";
                }
                $error.html(error_msg).show();
                enable($submitBtn);
            }
        });
    },

    hideWikiMenu: function() {
        this.newWikiMenu.hide();
        this.newWikiMenu = null;
    },

    showWikiMenu: function(event) {
        var container = $(event.target).closest('.add-wiki-container');
        var newWikiMenu = container.find('.sf-dropdown-menu');
        if (this.newWikiMenu) {
            this.newWikiMenu.hide();
            this.newWikiMenu = null;
            return false;
        }
        newWikiMenu.show();
        this.newWikiMenu = newWikiMenu;
        return false;
    }
}

NewWikiController.init();

</script>
{% endblock %}
