<%namespace name="components" file="/components.html"/>


<%def name="row(tile, comment)">
    <li class="tile">
        <div>
            <h3><a href="${h.entity_url(comment)}">${_("Comment") if h.comment.wording() else _("Argument")}</a>
                ${_("on %s") % h.delegateable.link(comment.topic)|n}</h3>
            <div class="meta">
                ${h.user.link(comment.creator, scope=comment.topic)|n}
                %if len(comment.revisions) == 1:
                    · ${_("created %s") % h.datetime_tag(comment.create_time)|n}
                %else:
                    · ${_("edited %s") % h.datetime_tag(comment.latest.create_time)|n}
                %endif
            </div>
        </div>
    </li>
</%def>


<%def name="list(tile, comments, topic, variant=None, root=None, recurse=True, came_from='')">
    <%
    _comments = h.comments_sorted(comments, root=root, variant=variant)
    %>

    <% auth = check.comment.create_on(topic) %>
    %if root is None:
        %if auth:

        <%
        hide_form = True
        target = 'new_toplevel_comment'
        if len(_comments) == 0:
             hide_form = False
        %>
        <div class="comment_wrapper"
             %if hide_form:
             style="display: none"
             %endif
             id="${target}"
             data-cancel=".cancel">
            <div class="comment">
                ${create_form(None, topic, variant=variant, came_from=came_from, show_cancel=(len(comments) != 0))}
            </div>
        </div>
        %if hide_form:
        <div class="list_button">
            <a class="button highlight showhide_button action"
               href="${h.base_url('/comment/new', topic.instance, query_params={'topic': topic.id, 'wiki': 1})}"
               data-target="#${target}"
               aria-controls="${target}"
               id="start-discussion-button">
                ${_('Add comment') if h.comment.wording() else _('Start new discussion')}
            </a>
        </div>
        %endif

        %elif auth.propose_join():
        <div class="list_button">
            <a class="button add ttip"
               href="${h.base_url('/comment/new', topic.instance, query_params={'topic': topic.id, 'wiki': 1})}"
               title="${_('Join instance to comment.') if h.comment.wording() else _('Join instance to discuss.')}"
               rel="#overlay-join-button">
                ${_("Add comment") if h.comment.wording() else _('Start new discussion')}
            </a>
        </div>
        %elif auth.propose_login():
        <div class="list_button">
            <a class="button add ttip"
               href="${h.base_url('/comment/new', topic.instance, query_params={'topic': topic.id, 'wiki': 1})}"
               title="${_('Login to comment.') if h.comment.wording() else _('Login to discuss.')}"
               rel="#overlay-login-button">
                ${_("Add comment") if h.comment.wording() else _('Start new discussion')}
            </a>
        </div>
        %elif auth.propose_validate_email():
        <div class="list_button">
            <a class="button add ttip"
               href="${h.base_url('/comment/new', topic.instance, query_params={'topic': topic.id, 'wiki': 1})}"
               title="${_('Validate email in order to comment.') if h.comment.wording() else _('Validate email in order to discuss.')}"
               rel="#overlay-validate-button">
                ${_("Add comment") if h.comment.wording() else _('Start new discussion')}
            </a>
        </div>
        %endif

    %endif

    %if root is None:
        %if not len(_comments):
            <div class="comment_wrapper">
                <div class="comment empty">
                    ${_("No comments were made yet.") if h.comment.wording() else _("No discussions were started yet.")}
                </div>
            </div>
        %endif
    %endif

    %if _comments:
    <ul id="${root is not None and 'c%s_comments' % root.id or ''}"
        class="${root is None and 'comments_list' or 'sub'}">
        %for comment, tile in _comments:
        %if tile.show:
        <li>
            ${tiles.comment.show(comment, recurse=recurse, came_from=came_from)}

            %if recurse:
            ${tiles.comment.list(comment.topic, comment, comment.topic.comments,  variant=variant, recurse=recurse, came_from=came_from)}
            %endif

        </li>
        %endif
        %endfor
    </ul>
    %endif
</%def>


<%def name="show(tile, comment, came_from='')">
    <%
    if not tile.show:
        return

    sentiment = {'css': '', 'msg': ''}
    if comment.latest.sentiment == model.Comment.SENT_PRO:
        sentiment = {'css': 'pro', 'msg': _(u'is pro')}
    elif comment.latest.sentiment == model.Comment.SENT_CON:
        sentiment = {'css': 'con', 'msg': _(u'is con')}
    %>

    <div id="c${comment.id}" class="comment">

        <div class="header">
            <h5>
                ## comment title (username / pro/con / deleted)
                %if not comment.is_deleted():
                    ${h.user.link(comment.creator, scope=comment.topic)|n}
                    <span class="${sentiment['css']}">${sentiment['msg']}</span>
                %else:
                <h5>${_("(deleted)")}</h5>
                %endif

                <span class="utility">
                    %if can.comment.edit(comment):
                    <a class="edit_comment"
                       href="${h.entity_url(comment, member='edit',
                                            query=dict(came_from=came_from))}">
                        ${_("edit")}</a>
                    %endif

                    %if can.comment.delete(comment):
                    <a class="" href="${h.entity_url(comment, member='ask_delete')}">${_("delete")}</a>
                    %endif
                </span>
            </h5>

            <div class="vote_comment">
                ${tiles.poll.widget(comment.poll)}
            </div>
        </div>

        ## comment text
        <div class="body">
            %if not comment.is_deleted():
            ${tile.text|n}
            %else:
            <span class="hint">${_("This comment has been deleted.") if h.comment.wording() else _("This argument has been deleted.")}</span>
            %endif
        </div>

        <div class="footer">
            <div class="utility">
                %if comment.is_deleted():
                ${_("deleted %s") % h.datetime_tag(comment.delete_time)|n}
                %else:
                  %if not comment.is_edited():
                  ${h.datetime_tag(comment.create_time)|n}
                  %else:
                    %if comment.latest.user == comment.creator:
                    ${_("edited %s") % h.datetime_tag(comment.latest.create_time)|n}
                    %else:
                    ${_("edited %s by %s") % (h.datetime_tag(comment.latest.create_time),
                    h.user.link(comment.latest.user, scope=comment.topic))|n}
                    %endif
                  %endif
                %endif

                <span class="utility_links">
                    %if len(comment.revisions) > 1:
                    <span class="only-js">
                        ·
                        ## FIXME: remove when we can support no-js clients.
                        <a href="${h.entity_url(comment, member='history')}"
                           rel="#overlay-url">${_("history")}</a>
                    </span>
                    %endif
                    %if h.config.get_bool('adhocracy.show_abuse_button'):
                    ·
                    <a href="${h.abuse.for_entity(comment)}">${_("report")}</a>
                    %endif
                    <%doc>
                    FIXME: Add when we have implemented permalinks or details overlay dialogs
                    <a href="#">Link</a> ·
                    FIXME: Add when we implemented details dialog
                    </%doc>
                </span>
            </div>

            <div>
                ## Reply button
                <% auth = check.comment.reply(comment) %>
                %if auth and recurse:
                <a class="new_comment" data-reply-url="${h.base_url('/comment/form/reply/' + str(comment.id), query_params={'came_from': came_from})}" href="#">${_('reply') if h.comment.wording() else _('Add argument')}</a>
                %elif auth.propose_join():
                <a class="new_comment" title="${_('Join instance to reply') if h.comment.wording() else _('Join instance to argue')}" rel="#overlay-join-button">${_('reply') if h.comment.wording() else _('Add argument')}</a>
                %elif auth.propose_login():
                <a class="new_comment" title="${_('Login to reply') if h.comment.wording() else _('Login to argue')}" rel="#overlay-login-button">${_('reply') if h.comment.wording() else _('Add argument')}</a>
                %elif auth.propose_validate_email():
                <a class="new_comment" title="${_('Validate email in order to reply') if h.comment.wording() else _('Validate email in order to argue')}" rel="#overlay-validate-button">${_('reply') if h.comment.wording() else _('Add argument')}</a>
                %endif
            </div>
        </div>
    </div>
</%def>

<%def name="edit_form(comment, came_from='')">

<%

sentiment = comment.latest.sentiment

def klass(sentiment_button):
    value = 'button_small'
    if sentiment_button == sentiment:
        value += ' active'
    return value

klass_pro = klass(1)
klass_neutral = klass(0)
klass_con = klass(-1)
%>
    <form name="new_comment" class="comment_form"
          method="POST" action="${h.entity_url(comment, comment_page=True)}">
        ${h.field_token()|n}
        <input type="hidden" name="_method" value="PUT" />
        <input type="hidden" name="came_from" value="${came_from}" />
      <div class="subcolumns">
        <div class="c60l">
          <div class="subcl">
            <textarea name="text">${comment.latest.text}</textarea>
            ${components.formatting()}
          </div>
        </div>
        <div class="c40r">
          <div class="subcr comment_settings">
            <% from adhocracy.model.page import Page %>
            %if comment.topic.function == Page.DESCRIPTION:
            <div class="input_wrapper comment_status only-js">
              ${_(u'Comment is...') if h.comment.wording() else _(u'Argument is...')}<br />
              <a class="${klass_pro}"
                 data-status="1" href="#">${_('Pro')}</a>
              <a class="${klass_neutral}"
                 data-status="0"
                 href="#">${_('Neutral')}</a>
              <a class="${klass_con}"
                 data-status="-1"
                 href="#">${_('Con')}</a>
              <input type="hidden" name="sentiment"
                     value="${str(comment.latest.sentiment)}" />
            </div>
            <hr />
            %endif
            <div class="input_wrapper submit">
              <input type="submit" value="${_('Save')}" />&nbsp;
              <a class="cancel"
                 href="${h.entity_url(comment.topic)}">${_("cancel")}</a>
            </div>
          </div>
        </div>
      </div>
    </form>

</%def>


<%def name="create_form(parent, topic, wiki=None, arm=False, can_wiki=True, variant=None, came_from='', format=None, show_cancel=True)">

<%
if format is None:
    format = ''
else:
    format = ".%s" % format

if wiki is None:
    wiki = c.instance.editable_comments_default
%>
    <form name="new_comment" class="comment_form"
        method="POST" action="${h.base_url('/comment%s' % format, topic.instance)}">
      ${h.field_token()|n}
      <input type="hidden" name="topic" value="${topic.id}" />
      <input type="hidden" name="came_from" value="${came_from}" />
      %if variant:
          <input type="hidden" name="variant" value="${variant}" />
      %endif
      %if parent:
          <input type="hidden" name="reply" value="${parent.id}" />
      %endif
      <div class="subcolumns">
        <div class="c60l">
          <div class="subcl">
            <textarea name="text"></textarea>
            ${components.formatting()}
          </div>
        </div>
        <div class="c40r">
          <div class="subcr comment_settings">
            <% from adhocracy.model.page import Page %>
            %if topic.function == Page.DESCRIPTION:
            <div class="input_wrapper comment_status only-js">
              ${_(u'Comment is...') if h.comment.wording() else _(u'Argument is...')}<br />
              <a class="button_small" data-status="1" href="#">${_('Pro')}</a>
              <a class="button_small" data-status="0" href="#">${_('Neutral')}</a>
              <a class="button_small" data-status="-1" href="#">${_('Con')}</a>
              <input type="hidden" name="sentiment" value="0" />
            </div>
            <hr />
            %endif
            <div class="input_wrapper">
              <label>
                  <input id="editable" name="wiki" type="checkbox"
                         ${'checked="checked"' if wiki else ''}/>
                  ${_("Allow others to edit this comment.") if h.comment.wording() else _("Allow others to edit this argument.")}
              </label>
            </div>
            <hr />
            <div class="input_wrapper submit">
              <input type="submit" value="${_('Save')}" />&nbsp;
              %if show_cancel:
              <a class="cancel"
                 href="${'/d/%s' % (parent.topic.id if parent else request.params.get('topic'))}">${_("cancel")}</a>
              %endif
            </div>
          </div>
        </div>
      </div>
    </form>

</%def>


<%def name="header(tile, comment, active)">
    <div class="top_actions title">
        %if can.comment.edit(comment):
            <a class="button edit" onClick="return adhocracy.comment_edit(${comment.id})"
                href="${h.entity_url(comment, member='edit')}">${_("edit")}</a>
        %endif

        %if can.comment.delete(comment):
            <a class="button delete"
                href="${h.entity_url(comment, member='ask_delete')}">${_("delete")}</a>
        %endif

        ${components.watch(comment)}
    </div>

    <h1 class="page_title">
         ${(_("Comments on %s") if h.comment.wording() else _("Discussion on %s") \
           ) % h.delegateable.link(comment.topic)|n}</h1>

    <div class="panel ${active}">
        <ul class="menu">
            <li><a href="${h.entity_url(comment)}">${_("Context")}</a></li>
            <li><a href="${h.entity_url(comment, comment_page=True)}"
                class="discussion">${_("Comment") if h.comment.wording() else _("Argument")}</a></li>
            <li><a href="${h.entity_url(comment, member='history')}"
                class="history">${_("History")} (${len(comment.revisions)})</a></li>
            <li><a href="${h.entity_url(comment.poll, member='votes')}"
                class="votes">${_("Votes")} (${len(comment.poll.tally)})</a></li>
        </ul>
    </div>
</%def>
