<%inherit file="/base/base.html"/>

<%def name="title()">
    ${_('%s Pull Request #%s') % (c.repo_name, c.pull_request.pull_request_id)}
    %if c.site_name:
        &middot; ${c.site_name}
    %endif
</%def>

<%def name="breadcrumbs_links()">
    ${_('Pull request #%s from %s#%s') % (c.pull_request.pull_request_id, c.pull_request.org_repo.repo_name, c.cs_branch_name)}
</%def>

<%def name="page_nav()">
    ${self.menu('repositories')}
</%def>

<%def name="main()">
${self.repo_context_bar('showpullrequest')}
<div class="box">
    <!-- box / title -->
    <div class="title">
        ${self.breadcrumbs()}
    </div>

    <div class="form pr-box" style="float: left">
      <div class="pr-details-title ${'closed' if c.pull_request.is_closed() else ''}">
          ${_('Title')}: ${c.pull_request.title}
          %if c.pull_request.is_closed():
              (${_('Closed')})
          %endif
      </div>
      <div id="pr-summary" class="fields">

        <div class="field pr-not-edit" style="min-height:37px">
          <div class="label-summary">
            <label>${_('Description')}:</label>
            %if not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin', 'repository.admin')() or c.pull_request.author.user_id == c.authuser.user_id):
            <div style="margin: 5px">
              <a class="btn btn-mini" onclick="YUD.setStyle('pr-edit-form','display','');YUD.setStyle(YUD.getElementsByClassName('pr-not-edit'),'display','none')">${_("Edit")}</a>
            </div>
            %endif
          </div>
          <div class="input">
            <div style="white-space:pre-wrap; line-height: 14px">${h.urlify_commit(c.pull_request.description, c.pull_request.org_repo.repo_name)}</div>
          </div>
        </div>

        %if not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin', 'repository.admin')() or c.pull_request.author.user_id == c.authuser.user_id):
        <div id="pr-edit-form" style="display:none">
          ${h.form(url('pullrequest_post', repo_name=c.repo_name, pull_request_id=c.pull_request.pull_request_id), method='post', id='pull_request_form')}

          <div class="field">
              <div class="label-summary">
                  <label for="pullrequest_title">${_('Title')}:</label>
              </div>
              <div class="input">
                  ${h.text('pullrequest_title',class_="large",value=c.pull_request.title,placeholder=_('Summarize the changes'))}
              </div>
          </div>

          <div class="field">
              <div class="label-summary label-textarea">
                  <label for="pullrequest_desc">${_('Description')}:</label>
              </div>
              <div class="textarea text-area editor">
                  ${h.textarea('pullrequest_desc',size=30,content=c.pull_request.description,placeholder=_('Write a short description on this pull request'))}
              </div>
              <div class="buttons">
                  ${h.submit('save',_('Save'),class_="btn btn-mini")}
                  ${h.reset('reset',_('Cancel'),class_="btn btn-mini",onclick="YUD.setStyle('pr-edit-form','display','none');YUD.setStyle(YUD.getElementsByClassName('pr-not-edit'),'display','')")}
             </div>
          </div>

          ${h.end_form()}
        </div>
        %endif

        <div class="field">
          <div class="label-summary">
              <label>${_('Reviewer voting result')}:</label>
          </div>
          <div class="input">
            <div class="changeset-status-container" style="float:none;clear:both">
            %if c.current_voting_result:
              <div class="changeset-status-ico" style="padding:0px 4px 0px 0px">
                  <img src="${h.url('/images/icons/flag_status_%s.png' % c.current_voting_result)}" title="${_('Pull request status calculated from votes')}"/></div>
              <div class="changeset-status-lbl tooltip" title="${_('Pull request status calculated from votes')}">
                %if c.pull_request.is_closed():
                    ${_('Closed')},
                %endif
                ${h.changeset_status_lbl(c.current_voting_result)}
              </div>

            %endif
            </div>
          </div>
        </div>
        <div class="field">
          <div class="label-summary">
              <label>${_('Still not reviewed by')}:</label>
          </div>
          <div class="input">
            % if len(c.pull_request_pending_reviewers) > 0:
                <div class="tooltip" title="${h.tooltip(', '.join([x.username for x in c.pull_request_pending_reviewers]))}">${ungettext('%d reviewer', '%d reviewers',len(c.pull_request_pending_reviewers)) % len(c.pull_request_pending_reviewers)}</div>
            % elif len(c.pull_request_reviewers) > 0:
                <div>${_('Pull request was reviewed by all reviewers')}</div>
            %else:
                <div>${_('There are no reviewers')}</div>
            %endif
          </div>
        </div>
        <div class="field">
          <div class="label-summary">
              <label>${_('Origin')}:</label>
          </div>
          <div class="input">
            <div>
              ${h.link_to_ref(c.pull_request.org_repo.repo_name, c.cs_ref_type, c.cs_ref_name, c.cs_rev)}
              %if c.cs_ref_type != 'branch':
                ${_('on')} ${h.link_to_ref(c.pull_request.org_repo.repo_name, 'branch', c.cs_branch_name)}
              %endif
            </div>
          </div>
        </div>
        <div class="field">
          <div class="label-summary">
              <label>${_('Target')}:</label>
          </div>
          <div class="input">
              <div>
              ${h.link_to_ref(c.pull_request.other_repo.repo_name, c.a_ref_type, c.a_ref_name)}
              ## we don't know other rev - c.a_rev is ancestor and not necessarily on other_name_branch branch
              </div>
          </div>
        </div>
        <div class="field">
          <div class="label-summary">
              <label>${_('Pull changes')}:</label>
          </div>
          <div class="input">
              <div>
               ## TODO: use cs_ranges[-1] or org_ref_parts[1] in both cases?
               %if h.is_hg(c.pull_request.org_repo):
                 <span style="font-family: monospace">hg pull ${c.pull_request.org_repo.clone_url()} -r ${h.short_id(c.cs_ranges[-1].raw_id)}</span>
               %elif h.is_git(c.pull_request.org_repo):
                 <span style="font-family: monospace">git pull ${c.pull_request.org_repo.clone_url()} ${c.pull_request.org_ref_parts[1]}</span>
               %endif
              </div>
          </div>
        </div>
        <div class="field">
          <div class="label-summary">
              <label>${_('Created on')}:</label>
          </div>
          <div class="input">
              <div>${h.fmt_date(c.pull_request.created_on)}</div>
          </div>
        </div>
        <div class="field">
          <div class="label-summary">
              <label>${_('Created by')}:</label>
          </div>
          <div class="input">
              <div class="author">
                  <div class="gravatar">
                      <img alt="gravatar" src="${h.gravatar_url(c.pull_request.author.email,20)}"/>
                  </div>
                  <span>${c.pull_request.author.username_and_name}</span><br/>
                  <span><a href="mailto:${c.pull_request.author.email}">${c.pull_request.author.email}</a></span><br/>
              </div>
          </div>
        </div>

        ${h.form(url('pullrequest_copy_update',repo_name=c.repo_name,pull_request_id=c.pull_request.pull_request_id), method='post')}
          <div class="field">
            <div class="label-summary">
              <label>${_('Update')}:</label>
            </div>
            <div class="input">
              <div class="msg-div">${c.update_msg}</div>
              %if c.available:
              <div style="max-height:200px; overflow-y:auto; overflow-x:hidden; margin-bottom: 10px">
                <table class="noborder">
                  %for cnt, cs in enumerate(reversed(c.available)):
                    <tr>
                    <td>${h.radio(name='updaterev', value=cs.raw_id)}</td>
                    <td>${h.link_to(h.show_id(cs),h.url('changeset_home',repo_name=c.cs_repo.repo_name,revision=cs.raw_id))}</td>
                    <td><div class="message" style="white-space:normal; height:1.1em; max-width: 500px; padding:0">${h.urlify_commit(cs.message, c.repo_name)}</div></td>
                    </tr>
                  %endfor
                </table>
              </div>
              %endif
              <div class="msg-div">${c.update_msg_other}</div>
            </div>
            %if c.available and not c.pull_request.is_closed():
              <div class="buttons">
                ${h.submit('copy_update',_('Create pull request update'),class_="btn btn-small")}
              </div>
            %endif
          </div>
        ${h.end_form()}

      </div>
    </div>
    ## REVIEWERS
    <div style="float:left; border-left:1px dashed #eee">
       <div class="pr-details-title">${_('Pull request reviewers')}</div>
        <div id="reviewers" style="padding:0px 0px 5px 10px">
          ## members goes here !
          <div>
            <ul id="review_members" class="group_members">
            %for member,status in c.pull_request_reviewers:
              <li id="reviewer_${member.user_id}">
                <div class="reviewers_member">
                    <div class="reviewer_status tooltip" title="${h.tooltip(h.changeset_status_lbl(status.status if status else 'not_reviewed'))}">
                      <img src="${h.url(str('/images/icons/flag_status_%s.png' % (status.status if status else 'not_reviewed')))}"/>
                    </div>
                  <div class="reviewer_gravatar gravatar"><img alt="gravatar" src="${h.gravatar_url(member.email,14)}"/> </div>
                  <div style="float:left;">${member.full_name} (${_('owner') if c.pull_request.user_id == member.user_id else _('reviewer')})</div>
                  <input type="hidden" value="${member.user_id}" name="review_members" />
                  %if not c.pull_request.is_closed() and (h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.user_id == c.authuser.user_id):
                  <div class="reviewer_member_remove action_button" onclick="removeReviewMember(${member.user_id})" title="${_('Remove reviewer')}">
                      <i class="icon-remove-sign" style="color: #FF4444;"></i>
                  </div>
                  %endif
                </div>
              </li>
            %endfor
            </ul>
          </div>
          %if not c.pull_request.is_closed():
          <div class='ac'>
            %if h.HasPermissionAny('hg.admin')() or h.HasRepoPermissionAny('repository.admin')(c.repo_name) or c.pull_request.author.user_id == c.authuser.user_id:
            <div class="reviewer_ac">
               ${h.text('user', class_='yui-ac-input',placeholder=_('Type name of reviewer to add'))}
               <div id="reviewers_container"></div>
            </div>
            <div style="padding:0px 10px">
             <span id="update_pull_request" class="btn btn-mini">${_('Save Changes')}</span>
            </div>
            %endif
          </div>
          %endif
        </div>
       </div>

    <div style="overflow: auto; clear: both">
      ##DIFF
      <div class="table" style="float:left;clear:none">
          <div class="diffblock">
              <div style="padding:5px">
                ${_('Compare view')}
              </div>
          </div>
          <div id="changeset_compare_view_content">
              ##CS
              <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">${ungettext('Showing %s commit','Showing %s commits', len(c.cs_ranges)) % len(c.cs_ranges)}</div>
              <%include file="/compare/compare_cs.html" />

              <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">
              ${_('Common ancestor')}:
              ${h.link_to(h.short_id(c.a_rev),h.url('changeset_home',repo_name=c.a_repo.repo_name,revision=c.a_rev))}
              </div>

              ## FILES
              <div style="font-size:1.1em;font-weight: bold;clear:both;padding-top:10px">

              % if c.limited_diff:
                  ${ungettext('%s file changed', '%s files changed', len(c.files)) % len(c.files)}
              % else:
                  ${ungettext('%s file changed with %s insertions and %s deletions','%s files changed with %s insertions and %s deletions', len(c.files)) % (len(c.files),c.lines_added,c.lines_deleted)}:
              %endif

              </div>
              <div class="cs_files">
                %if not c.files:
                   <span class="empty_data">${_('No files')}</span>
                %endif
                %for fid, change, f, stat in c.files:
                    <div class="cs_${change}">
                      <div class="node">${h.link_to(h.safe_unicode(f),'#' + fid)}</div>
                      <div class="changes">${h.fancy_file_stats(stat)}</div>
                    </div>
                %endfor
              </div>
              <div class="comments-number pr-comments-number">${ungettext("%d comment", "%d comments", len(c.comments)) % len(c.comments)} ${ungettext("(%d inline)", "(%d inline)", c.inline_cnt) % c.inline_cnt} <span class="firstlink"></span> </div>
              % if c.limited_diff:
                <h5>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h5>
              % endif
          </div>
      </div>
    </div>
    <script>
    var _USERS_AC_DATA = ${c.users_array|n};
    var _GROUPS_AC_DATA = ${c.user_groups_array|n};
    // TODO: switch this to pyroutes
    AJAX_COMMENT_URL = "${url('pullrequest_comment',repo_name=c.repo_name,pull_request_id=c.pull_request.pull_request_id)}";
    AJAX_COMMENT_DELETE_URL = "${url('pullrequest_comment_delete',repo_name=c.repo_name,comment_id='__COMMENT_ID__')}";

    pyroutes.register('pullrequest_comment', "${url('pullrequest_comment',repo_name='%(repo_name)s',pull_request_id='%(pull_request_id)s')}", ['repo_name', 'pull_request_id']);
    pyroutes.register('pullrequest_comment_delete', "${url('pullrequest_comment_delete',repo_name='%(repo_name)s',comment_id='%(comment_id)s')}", ['repo_name', 'comment_id']);
    pyroutes.register('pullrequest_update', "${url('pullrequest_update',repo_name='%(repo_name)s',pull_request_id='%(pull_request_id)s')}", ['repo_name', 'pull_request_id']);

    </script>

    ## diff block
    <%namespace name="diff_block" file="/changeset/diff_block.html"/>
    ${diff_block.diff_block_js()}
    %for fid, change, f, stat in c.files:
      ${diff_block.diff_block_simple([c.changes[fid]])}
    %endfor
    % if c.limited_diff:
      <h4>${_('Changeset was too big and was cut off...')} <a href="${h.url.current(fulldiff=1, **request.GET.mixed())}">${_('Show full diff anyway')}</a></h4>
    % endif


    ## template for inline comment form
    <%namespace name="comment" file="/changeset/changeset_file_comment.html"/>
    ${comment.comment_inline_form()}

    ## render comments and inlines
    ${comment.generate_comments()}

    ## main comment form and it status
    ${comment.comments(h.url('pullrequest_comment', repo_name=c.repo_name,
                              pull_request_id=c.pull_request.pull_request_id),
                       c.current_voting_result,
                       is_pr=True, change_status=c.allowed_to_change_status)}

    <script type="text/javascript">
      $(document).ready(function(){
          PullRequestAutoComplete('user', 'reviewers_container', _USERS_AC_DATA, _GROUPS_AC_DATA);

          YUE.on(YUQ('.show-inline-comments'),'change',function(e){
              var show = 'none';
              var target = e.currentTarget;
              if(target.checked){
                  var show = ''
              }
              var boxid = YUD.getAttribute(target,'id_for');
              var comments = YUQ('#{0} .inline-comments'.format(boxid));
              for(c in comments){
                 YUD.setStyle(comments[c],'display',show);
              }
              var btns = YUQ('#{0} .inline-comments-button'.format(boxid));
              for(c in btns){
                  YUD.setStyle(btns[c],'display',show);
               }
          })

          YUE.on(YUQ('.add-bubble'),'click',function(e){
              var tr = e.currentTarget;
              injectInlineForm(tr.parentNode.parentNode);
          });

          // inject comments into they proper positions
          var file_comments = YUQ('.inline-comment-placeholder');
          renderInlineComments(file_comments);

          linkInlineComments(document.getElementsByClassName('firstlink'), document.getElementsByClassName("inline-comment"));

          YUE.on(YUD.get('update_pull_request'),'click',function(e){
              updateReviewers(undefined, "${c.repo_name}", "${c.pull_request.pull_request_id}");
          })

          // hack: re-navigate to target after JS is done ... if a target is set and setting href thus won't reload
          if (window.location.hash != "") {
              window.location.href = window.location.href;
          }
      })
    </script>

</div>

</%def>
