<%inherit file="/base/base.html"/>
<%namespace name="changelog_table" file="/changelog/changelog_table.html"/>

<%block name="title">
    ${_('%s Summary') % c.repo_name}
</%block>

<%def name="breadcrumbs_links()">
    ${_('Summary')}

    ##FORK
    %if c.db_repo.fork:
        - <i class="icon-fork"></i>${_('Fork of')} "<a href="${h.url('summary_home',repo_name=c.db_repo.fork.repo_name)}">${c.db_repo.fork.repo_name}</a>"
    %endif

    ##REMOTE
    %if c.db_repo.clone_uri:
       - <i class="icon-fork"></i>${_('Clone from')} "<a href="${h.url(str(h.credentials_filter(c.db_repo.clone_uri)))}">${h.credentials_filter(c.db_repo.clone_uri)}</a>"
    %endif
</%def>

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

<%block name="head_extra">
  <link href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=request.authuser.api_key)}" rel="alternate" title="${_('%s ATOM feed') % c.repo_name}" type="application/atom+xml" />
  <link href="${h.url('rss_feed_home',repo_name=c.db_repo.repo_name,api_key=request.authuser.api_key)}" rel="alternate" title="${_('%s RSS feed') % c.repo_name}" type="application/rss+xml" />

  <script>
  'use strict';
  function redirect_hash_branch(){
    var branch = window.location.hash.replace(/^#(.*)/, '$1');
    if (branch){
      window.location = ${h.js(h.url('changelog_home',repo_name=c.repo_name,branch='__BRANCH__'))}
        .replace('__BRANCH__',branch);
    }
  }
  redirect_hash_branch();
  window.onhashchange = function() {
    redirect_hash_branch();
  };
  </script>
</%block>

<%def name="main()">
${self.repo_context_bar('summary')}
<div class="panel panel-primary">
    <div class="panel-heading clearfix">
        ${self.breadcrumbs()}
    </div>
    <div id="summary-panel-body" class="form panel-body">
        <div id="summary" class="pull-left">
            <div class="form-group form-inline">
                <label>${_('Clone URL')}:</label>
                <div id="clone-url">
                  <div id="clone_by_name" class="input-group" style="${'display:none' if c.ssh_repo_url else ''}">
                    <span class="input-group-addon">${self.repolabel(c.db_repo.repo_type)}</span>
                    <input class="form-control" size="80" readonly="readonly" value="${c.clone_repo_url}"/>
                    <span class="input-group-addon btn use-id">${_('Use ID')}</span>
                    %if c.ssh_repo_url:
                    <span class="input-group-addon btn use-ssh">${_('Use SSH')}</span>
                    %endif
                  </div>
                  <div id="clone_by_id" class="input-group" style="display:none">
                    <span class="input-group-addon">${self.repolabel(c.db_repo.repo_type)}</span>
                    <input class="form-control" size="80" readonly="readonly" value="${c.clone_repo_url_id}"/>
                    <span class="input-group-addon btn use-name">${_('Use Name')}</span>
                    %if c.ssh_repo_url:
                    <span class="input-group-addon btn use-ssh">${_('Use SSH')}</span>
                    %endif
                  </div>
                  %if c.ssh_repo_url:
                  <div id="clone_ssh" class="input-group">
                    <span class="input-group-addon">${self.repolabel(c.db_repo.repo_type)}</span>
                    <input id="ssh_url" class="form-control" size="80" readonly="readonly" value="${c.ssh_repo_url}"/>
                    <span class="input-group-addon btn use-name">${_('Use HTTP')}</span>
                  </div>
                  %endif
                </div>
            </div>

            <div class="form-group">
              <label>${_('Description')}:</label>
              <div class="formatted-fixed">${h.urlify_text(c.db_repo.description, stylize=c.visual.stylify_metalabels)}</div>
            </div>

            <div class="form-group">
              <label>${_('Trending files')}:</label>
              <div>
                %if c.show_stats:
                <div id="lang_stats"></div>
                %else:
                   ${_('Statistics are disabled for this repository')}
                   %if h.HasPermissionAny('hg.admin')('enable stats on from summary'):
                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_statistics'),class_="btn btn-default btn-xs")}
                   %endif
                %endif
              </div>
            </div>

            <div class="form-group">
              <label>${_('Download')}:</label>
              <div class="form-inline">
                %if len(c.db_repo_scm_instance.revisions) == 0:
                  ${_('There are no downloads yet')}
                %elif not c.enable_downloads:
                  ${_('Downloads are disabled for this repository')}
                    %if h.HasPermissionAny('hg.admin')('enable downloads on from summary'):
                        ${h.link_to(_('Enable'),h.url('edit_repo',repo_name=c.repo_name, anchor='repo_enable_downloads'),class_="btn btn-default btn-xs")}
                    %endif
                %else:
                    <span id="${'zip_link'}">
                        <a class="btn btn-default btn-sm" href="${h.url('files_archive_home',repo_name=c.db_repo.repo_name,fname='tip.zip')}"><i class="icon-file-zip"></i>${_('Download as zip')}</a>
                    </span>
                    ${h.hidden('download_options', class_='form-control')}
                    <span>
                      <label data-toggle="tooltip" title="${_('Check this to download archive with subrepos')}">
                          <input id="archive_subrepos" type="checkbox" name="subrepos" />
                          ${_('With subrepos')}
                      </label>
                    </span>
                %endif
              </div>
            </div>
        </div>
        <ul id="summary-menu-stats" class="list-group pull-right">
            <li class="list-group-item">
              <a title="${_('Owner')} ${c.db_repo.owner.email}">
                <i class="icon-user"></i>${c.db_repo.owner.username}
                ${h.gravatar_div(c.db_repo.owner.email, size=18, div_class="pull-right")}
              </a>
            </li>
            <li class="list-group-item">
              <a title="${_('Followers')}" href="${h.url('repo_followers_home',repo_name=c.repo_name)}">
                <i class="icon-heart"></i>${_('Followers')}
                <span class="badge pull-right" id="current_followers_count">${c.repository_followers}</span>
              </a>
            </li>
            <li class="list-group-item">
              <a title="${_('Forks')}" href="${h.url('repo_forks_home',repo_name=c.repo_name)}">
                <i class="icon-fork"></i>${_('Forks')}
                <span class="badge pull-right">${c.repository_forks}</span>
              </a>
            </li>

            %if request.authuser.username != 'default':
            <li class="list-group-item clearfix">
              <a href="#" onclick="javascript:showRepoSize('repo_size_2','${c.db_repo.repo_name}')">
                <i class="icon-ruler"></i>${_('Size')}
                <span class="badge pull-right" id="repo_size_2"></span>
              </a>
            </li>
            %endif

            <li class="list-group-item">
            %if request.authuser.username != 'default':
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name,api_key=request.authuser.api_key)}"><i class="icon-rss-squared"></i>${_('Feed')}</a>
            %else:
              <a href="${h.url('atom_feed_home',repo_name=c.db_repo.repo_name)}"><i class="icon-rss-squared"></i>${_('Feed')}</a>
            %endif
            </li>

            %if c.show_stats:
            <li class="list-group-item">
              <a title="${_('Statistics')}" href="${h.url('repo_stats_home',repo_name=c.repo_name)}">
                <i class="icon-graph"></i>${_('Statistics')}
              </a>
            </li>
            %endif
        </ul>
    </div>
</div>


<div class="panel panel-primary">
    <div class="panel-heading">
        <div class="panel-title">
        %if c.cs_pagination:
            ${h.link_to(_('Latest Changes'),h.url('changelog_home',repo_name=c.repo_name))}
        %else:
            ${_('Quick Start')}
        %endif
        </div>
    </div>
    <div class="panel-body">
        <div id="shortlog_data">
            %if c.cs_pagination:
                ${changelog_table.changelog(c.repo_name, c.cs_pagination, c.cs_statuses, c.cs_comments, show_checkbox=False)}
                ${c.cs_pagination.pager()}
            %else:
                %if h.HasRepoPermissionLevel('write')(c.repo_name):
                <h4>${_('Add or upload files directly via Kallithea')}</h4>
                <div>
                  <div id="add_node_id" class="add_node">
                      <a class="btn btn-default btn-xs" href="${h.url('files_add_home',repo_name=c.repo_name,revision=0,f_path='', anchor='edit')}">${_('Add New File')}</a>
                  </div>
                </div>
                %endif

                <h4>${_('Push new repository')}</h4>
                <pre>
${c.db_repo_scm_instance.alias} clone ${c.clone_repo_url}
${c.db_repo_scm_instance.alias} add README # add first file
${c.db_repo_scm_instance.alias} commit -m "Initial" # commit with message
${c.db_repo_scm_instance.alias} push ${'origin master' if c.db_repo_scm_instance.alias == 'git' else ''} # push changes back
                </pre>

                <h4>${_('Existing repository?')}</h4>
                <pre>
                %if c.db_repo_scm_instance.alias == 'git':
git remote add origin ${c.clone_repo_url}
git push -u origin master
                %else:
hg push ${c.clone_repo_url}
                %endif
                </pre>
            %endif
        </div>
    </div>
</div>

%if c.readme_data:
<div id="readme" class="anchor">
</div>
<div class="panel panel-primary">
    <div class="panel-heading" title="${_('Readme file from revision %s:%s') % (c.db_repo.landing_rev[0], c.db_repo.landing_rev[1])}">
        <div class="panel-title">
            <a href="${h.url('files_home',repo_name=c.repo_name,revision='tip',f_path=c.readme_file)}">${c.readme_file}</a>
        </div>
    </div>
    <div class="readme panel-body">
        ${c.readme_data|n}
    </div>
</div>
%endif

<script>
'use strict';
$(document).ready(function(){
    $('#clone-url input').click(function(){
        if($(this).hasClass('selected')){
            $(this).removeClass('selected');
            return ;
        }else{
            $(this).addClass('selected');
            $(this).select();
        }
    });

    var $clone_url = $('#clone-url');
    var $clone_by_name = $('#clone_by_name');
    var $clone_by_id = $('#clone_by_id');
    var $clone_ssh = $('#clone_ssh');
    $clone_url.on('click', '.btn.use-name', function(){
        $clone_by_name.show();
        $clone_by_id.hide();
        $clone_ssh.hide();
    });
    $clone_url.on('click', '.btn.use-id', function(){
        $clone_by_id.show();
        $clone_by_name.hide();
        $clone_ssh.hide();
    });
    $clone_url.on('click', '.btn.use-ssh', function(){
        $clone_by_id.hide();
        $clone_by_name.hide();
        $clone_ssh.show();
    });

    var cache = {}
    $("#download_options").select2({
        placeholder: _TM['Select changeset'],
        dropdownAutoWidth: true,
        query: function(query){
          var key = 'cache';
          var cached = cache[key] ;
          if(cached) {
            var data = {results: []};
            //filter results
            $.each(cached.results, function(){
                var section = this.text;
                var children = [];
                $.each(this.children, function(){
                    if(query.term.length == 0 || this.text.toUpperCase().indexOf(query.term.toUpperCase()) >= 0 ){
                        children.push({'id': this.id, 'text': this.text});
                    }
                });
                data.results.push({'text': section, 'children': children});
            });
            query.callback(data);
          }else{
              $.ajax({
                url: pyroutes.url('repo_refs_data', {'repo_name': ${h.js(c.repo_name)}}),
                data: {},
                dataType: 'json',
                type: 'GET',
                success: function(data) {
                  cache[key] = data;
                  query.callback({results: data.results});
                }
              });
          }
        }
    });
    // on change of download options
    $('#download_options').change(function(e){
       var new_cs = e.added

       for(let k in tmpl_links){
           var s = $('#'+k+'_link');
           if(s){
             var title_tmpl = ${h.jshtml(_('Download %s as %s') % ('__CS_NAME__','__CS_EXT__'))};
             title_tmpl= title_tmpl.replace('__CS_NAME__',new_cs.text);
             title_tmpl = title_tmpl.replace('__CS_EXT__',k);
             title_tmpl = '<i class="icon-file-zip"></i>'+ title_tmpl.html_escape();
             var url = tmpl_links[k].replace('__CS__',new_cs.id);
             var subrepos = $('#archive_subrepos').is(':checked');
             url = url.replace('__SUB__',subrepos);
             url = url.replace('__NAME__',title_tmpl);

             s.html(url);
           }
       }
    });

    var tmpl_links = {};
    %for cnt,archive in enumerate(c.db_repo_scm_instance._get_archives()):
      tmpl_links[${h.jshtml(archive['type'])}] = ${h.js(h.link_to('__NAME__', h.url('files_archive_home',repo_name=c.db_repo.repo_name, fname='__CS__'+archive['extension'],subrepos='__SUB__'),class_='btn btn-default btn-sm'))};
    %endfor
});
</script>

%if c.show_stats:
<script>
'use strict';
$(document).ready(function(){
    var data = ${h.js(c.trending_languages)};
    var total = 0;
    var tbl = document.createElement('table');
    tbl.setAttribute('class','table');
    var cnt = 0;
    for (let i=0;i<data.length;i++){
        total+= data[i][1].count;
    }
    for (let i=0;i<data.length;i++){
        cnt += 1;

        var hide = cnt>2;
        var tr = document.createElement('tr');
        if (hide){
            tr.setAttribute('style','display:none');
            tr.setAttribute('class','stats_hidden');
        }
        var k = data[i][0];
        var obj = data[i][1];
        var percentage = Math.round((obj.count/total*100),2);

        var td1 = document.createElement('td');
        td1.width = 250;
        var trending_language_label = document.createElement('div');
        trending_language_label.innerHTML = obj.desc+" ("+k+")";
        td1.appendChild(trending_language_label);

        var td2 = document.createElement('td');
        td2.setAttribute('style','padding-right:14px !important');
        var trending_language = document.createElement('div');
        var nr_files = obj.count + ' ' + ${h.jshtml(_('files'))};

        trending_language.title = k+" "+nr_files;

        if (percentage>22){
            trending_language.innerHTML = "<b class='progress-bar' role='progressbar'"
                + "aria-valuemin='0' aria-valuemax='100' aria-valuenow='" + percentage
                + "' style='width: " + percentage + "%;'>" + percentage + "%, " + nr_files + "</b>";
        }
        else if (percentage>5){
            trending_language.innerHTML = "<b class='progress-bar' role='progressbar'"
                + "aria-valuemin='0' aria-valuemax='100' aria-valuenow='" + percentage
                + "' style='width: " + percentage + "%;'>" + percentage + "%</b>";
        }else{
            trending_language.innerHTML = "<b class='progress-bar' role='progressbar'"
                + "aria-valuemin='0' aria-valuemax='100' aria-valuenow='" + percentage
                + "' style='width: " + percentage + "%;'>&nbsp;</b>&nbsp;" + percentage + "%";
        }

        td2.appendChild(trending_language);

        tr.appendChild(td1);
        tr.appendChild(td2);
        tbl.appendChild(tr);
        if(cnt == 3){
            var show_more = document.createElement('tr');
            var td = document.createElement('td');
            let lnk = document.createElement('a');

            lnk.href='#';
            lnk.innerHTML = ${h.jshtml(_('Show more'))};
            lnk.id='code_stats_show_more';
            td.appendChild(lnk);

            show_more.appendChild(td);
            show_more.appendChild(document.createElement('td'));
            tbl.appendChild(show_more);
        }

    }
    if (data.length == 0) {
        tbl.innerHTML = '<tr><td>' + ${h.jshtml(_('No data ready yet'))} + '</td></tr>';
    }

    $('#lang_stats').append(tbl);
    $('#code_stats_show_more').click(function(){
        $('.stats_hidden').show();
        $('#code_stats_show_more').hide();
    });
});
</script>
%endif

</%def>
