{% extends "repo_master.html" %}

{% block title %}Branches - {{
    repo.namespace + '/' if repo.namespace }}{{ repo.name }}{% endblock %}
{% set tag = "home" %}

{% block repo %}
<div class="row">
  <div class="col-2">
    {% block overviewtabs %}{{ super() }}{% endblock %}
  </div>
  <div class="col-10">
    <h3 class="font-weight-bold">
      Branches <span class="badge badge-secondary">{{g.branches|length}}</span>
    </h3>
    <div class="list-group">
      {% if head %}
      <div id="branch-{{ head }}" class="list-group-item">
        <div class="row align-items-center">
          <div class="col">
            <span class="fa fa-random fa-fw text-muted"></span>
            <a href="{{ url_for('ui_ns.view_tree',
              repo=repo.name,
              username=username,
              namespace=repo.namespace,
              identifier=head) }}"
              title="{{ head }}" data-toggle="tooltip"
              class="font-weight-bold">
              {{ head }}
            </a>
          </div>
          <div class="col-xs-auto pl-2">
            <button class="btn btn-outline-light bg-white border-white" title="this is the default branch for this project">
            <span class="fa fa-star fa-fw text-warning"></span>
            </button>
          </div>
        </div>
      </div>
      {% endif %}

      {% for branch in g.branches if branch != head %}
        <div id="branch-{{ branch | unicode | replace('/', '__')}}" class="list-group-item">
          <div class="row align-items-center">
            <div class="col">
              <span class="fa fa-random fa-fw text-muted"></span>
              <a class="font-weight-bold" href="{{ url_for('ui_ns.view_tree',
                repo=repo.name,
                username=username,
                namespace=repo.namespace,
                identifier=branch) }}"
                title="{{ branch | unicode }}" data-toggle="tooltip">{{ branch | unicode }}
              </a>
              <small class="text-muted commits_ahead_label"></small>
            </div>
            <div class="col-xs-auto pr-2">
              <div class="branch_del">
                <div class="btn-group">
                    <a class="btn btn-outline-primary" href="{{ url_for('ui_ns.view_tree',
                      repo=repo.name,
                      username=username,
                      namespace=repo.namespace,
                      identifier=branch) }}"
                      title="view code tree for this branch">
                    <i class="fa fa-fw fa-file-code-o"></i>
                    </a>
                    <a class="btn btn-outline-primary" href="{{ url_for('ui_ns.view_commits',
                      repo=repo.name,
                      username=username,
                      namespace=repo.namespace,
                      identifier=branch,
                      branchname=branch) }}"
                      title="view commit list for this branch">
                    <i class="fa fa-fw fa-list-alt"></i>
                    </a>
                </div>
                {% if g.repo_committer and branch != head
                      and (
                        config.get('ALLOW_DELETE_BRANCH', True)
                        or repo.is_fork) %}
                  <form id="delete_branch_form-{{
                      branch | unicode | replace('/', '__') | replace('+', '___')
                    }}" action="{{
                    url_for('ui_ns.delete_branch',
                            repo=repo.name,
                            username=username,
                            namespace=repo.namespace,
                            branchname=branch)
                    }}" method="post" class="icon d-inline delete-branch-form"
                    data-branch-name="{{ branch | unicode }}">
                    {{ g.confirmationform.csrf_token }}
                    <a title="Remove branch {{ branch | unicode }}" href="#"
                      class="btn btn-outline-danger delete-branch-btn"
                      data-branch-name="{{
                        branch | unicode | replace('/', '__') | replace('.', '\\\\.')
                        | replace('+', '___')
                        }}">
                      <i class="fa fa-trash"></i>
                    </a>
                  </form>
                {% endif %}
              </div>
            </div>
          </div>
        </div>
      {% endfor %}
    </div>
  </div>
</div>
{% endblock %}

{% block jscripts %}
{{ super() }}
<script type="text/javascript" nonce="{{ g.nonce }}">
$(function() {
  {% if g.authenticated and g.repo_committer %}

  $(".delete-branch-btn").click(function() {
    $('#delete_branch_form-' + $(this).attr("data-branch-name")).submit()
  });

  $(".delete-branch-form").submit(function() {
    console.log($(this));
    return confirm('Are you sure you want to remove the branch: ' + $(this).attr("data-branch-name") + '?\nThis cannot be un-done!');
  });

  var _cnt = 0;

  function set_up_branch_pr_info(res) {
    for (branch in res.new_branch){
      var nb_commits = res.new_branch[branch]['commits']
      var nb_target = res.new_branch[branch]['target_branch']
      var url = "{{ url_for(
        'ui_ns.new_request_pull',
        repo=repo.name,
        username=repo.user.user if repo.is_fork else None,
        namespace=repo.namespace,
        branch_to='.',
        branch_from='.') }}";
      url = url.slice(0, -4) + nb_target + '..' + branch

      {% if repo.is_fork %}
      html2 = ' \
        <a class="btn btn-outline-primary border-white" data-toggle="tooltip" \
        href="' + url + '" title="' + branch +' contains '
         + nb_commits + ' commit not in the upstream project '
         + nb_target + ' branch. Click to create new PR now.'
         + '"><i class="fa fa-fw fa-arrow-circle-down"></i> Open Pull Request</a> \
        </div>';
      {% else %}
      html2 = ' \
        <a class="btn btn-outline-primary border-white" data-toggle="tooltip" \
        href="' + url + '" title="' + branch +' contains '
         + nb_commits + ' commit not in the ' + nb_target
         + ' branch. Click to create new PR now.'
         + '"><i class="fa fa-fw fa-arrow-circle-down"></i> Open Pull Request</a> \
        </div>';
      {%endif%}
      var _b = branch.replace(/\./g, '\\.').replace('/', '__').replace('\+', '\\+');
      $('#branch-' + _b + ' .branch_del').prepend(html2);
      $('[data-toggle="tooltip"]').tooltip({placement : 'bottom'});
      var commits_string = (nb_commits > 1) ? " commits" : " commit"
      $('#branch-' + _b + ' .commits_ahead_label').append(nb_commits + commits_string + ' ahead');
    }

    for (branch in res.branch_w_pr){
      var html = ' \
        <a class="btn btn-outline-success border-white" data-toggle="tooltip" '
         + 'href="{{ request.url_root }}' + res.branch_w_pr[branch]
         + '"title="' + branch +' is already in an opened pull-request">'
         + '<i class="fa fa-fw fa-arrow-circle-down"></i> Pull Request #' + res.branch_w_pr[branch].split('/').slice(-1)[0]  + ' </a> \
        </div>';
      $('#branch-' + branch.replace(/\./g, '\\.').replace('/', '__')
        + ' .branch_del').prepend(html);
      $('[data-toggle="tooltip"]').tooltip({placement : 'bottom'});
    }
  }

  function process_task_results(_data, callback) {
    var _url = '{{ url_for("internal_ns.task_info", taskid='') }}' + _data.task;
    $.ajax({
      url: _url ,
      type: 'GET',
      data: {
        js: 1,
        count: _cnt,
      },
      dataType: 'JSON',
      success: function(res) {
        callback(res.results);
        $("#spinnergif").hide();
      },
      error: function(res) {
        _cnt += 1;
        if (_cnt < 600) {
          window.setTimeout(process_task_results, 1000, _data, callback);
        }
      }
    });
  }


  $.ajax({
    url: '{{ url_for("internal_ns.get_pull_request_ready_branch") }}' ,
    type: 'POST',
    data: {
      namespace: "{{ repo.namespace if repo.namespace }}",
      repo: "{{ repo.name }}",
      repouser: "{{ repo.user.user if repo.is_fork else '' }}",
      csrf_token: "{{ g.confirmationform.csrf_token.current_token }}",
    },
    dataType: 'json',
    success: function(res) {
      if (res.code == 'OK'){
        process_task_results(res, set_up_branch_pr_info)
      }
    }
  });
  {% endif %}
});
</script>
{% endblock %}
