{% extends "repo_master.html" %}
{% from "_formhelper.html" import render_bootstrap_field %}

{% block title %}{% if not type or type == 'new'
    %}New issue{% elif type and type == 'edit'
    %}Edit issue #{{ issueid }} {% endif %} - {{
    repo.namespace + '/' if repo.namespace }}{{ repo.name }}{% endblock %}
{% set tag = "home" %}

{% block header %}
<link type="text/css" rel="stylesheet" nonce="{{ g.nonce }}" href="{{
  url_for('static', filename='vendor/emojione/emojione.sprites.css') }}?version={{ g.version}}"/>
<link type="text/css" rel="stylesheet" nonce="{{ g.nonce }}" href="{{
  url_for('static', filename='vendor/jquery.atwho/jquery.atwho.css') }}?version={{ g.version}}"/>
<link type="text/css" rel="stylesheet" nonce="{{ g.nonce }}" href="{{
  url_for('static', filename='vendor/selectize/selectize.bootstrap3.css') }}?version={{ g.version}}"/>
{% endblock %}


{% block repo %}
  {% if not type or type == 'new' %}
  <form action="{{ url_for('ui_ns.new_issue',
        repo=repo.name,
        username=username,
        namespace=repo.namespace)
    }}" method="post" enctype="multipart/form-data">

  {% elif type and type == 'edit' %}
  <form action="{{ url_for('ui_ns.edit_issue',
        repo=repo.name,
        username=username,
        namespace=repo.namespace,
        issueid=issueid) }}" method="post"
        enctype="multipart/form-data">
  {% endif %}
  {{form.csrf_token}}
  <div class="row">
  {% if (g.repo_user and not type) or (g.repo_user and type == 'new') %}
  <div class="col-12">
    <h4 class="font-weight-bold mb-4">New Issue</h4>
  </div>
  <div class="col-md-8">
  {% else %}
  <div class="col-md-8 mx-auto">
      {% if not type or type == 'new' %}
      <h4 class="font-weight-bold mb-4">New Issue</h4>
      {% elif type and type == 'edit' %}
      <h4 class="font-weight-bold mb-4">Edit Issue</h4>
      {% endif %}
  {% endif %}
    <div>

        {% if contributing %}
        <div id="contributing">
          {{ contributing | markdown | noJS | safe}}
        </div>
        {% endif %}

        {% if type == 'edit' %}
          {{ form.status(class_="hidden") }}
          <div class="d-flex align-items-center">
            <h4 class="mb-0 pr-1"><i class="fa fa-fw text-success fa-exclamation-circle"></i></h4>
            <h4 class="text-success font-weight-bold mb-0 pr-1">#{{issue.id}}</h4>
        {% endif %}
        {{ form.title(class_="form-control", placeholder="Issue Title", tabindex=1, required="required")|safe }}
        {% if form.title.errors %}
        <span class="float-right text-danger">
          <small>
          {% for error in form.title.errors %}
            {{ error }}&nbsp;
          {% endfor %}
          </small>
        </span>
        {% endif %}
        {% if type == 'edit' %}
          </div>
        {% endif %}

        <div class="card mt-2">
            <div class="card-header pb-0 pt-1 bg-light">
              <div class="row">
                <div class="col align-self-center">
                </div>
                <div class="col d-flex">
                  {% if types %}
                  {% if (types | length == 1 and not default) or (types | length > 1)%}
                  <div class="btn-group ml-auto" data-toggle="tooltip" data-placement="bottom" title="" data-original-title="">
                      <button title="Issue Templates" type="button" class="btn btn-outline-secondary border-0 dropdown-toggle qr-btn" data-toggle="dropdown" aria-expanded="false">
                        <span class="fa fa-list-ul"></span> Types <span class="caret"></span>
                      </button>
                      <div class="dropdown-menu dropdown-menu-right" x-placement="bottom-end" id="issue_templates_dropdown">
                          <div class="dropdown-header">Issue Templates</div>
                          {% for type in types %}
                          <a class="issue-template dropdown-item pointer" data-value="{{type}}">{{type}}</a>
                        {% endfor %}

                      </div>
                    </div>
                  {% else %}
                    {% set notemplates = True %}
                  {% endif %}
                  {% else %}
                    {% set notemplates = True %}
                  {% endif %}
                  <ul class="nav nav-tabs {{'ml-auto' if notemplates}} border-bottom-0">
                    <li class="nav-item">
                      <a class="nav-link pointer" id="previewinmarkdown">Preview</a>
                    </li>
                    <li class="nav-item">
                      <a class="nav-link active pointer" id="editinmarkdown">Edit</a>
                    </li>
                  </ul>
                </div>
              </div>
            </div>
            <div class="card-body">
              <textarea class="form-control" rows=8 id="issue_content" name="issue_content"
                placeholder="Enter your comment here" tabindex=2 required>
                {%- if issue %}{{ issue.content }}{%
                  elif form.issue_content.data %}{{ form.issue_content.data }}{%
                  elif default %}{{ default }}{%
              endif -%}
              </textarea>
              {% if form.issue_content.errors %}
              <span class="float-right text-danger">
                <small>
                {% for error in form.issue_content.errors %}
                  {{ error }}&nbsp;
                {% endfor %}
                </small>
              </span>
              {% endif %}
                <div id="preview" class="p-1">
                </div>
                <div class="mt-2">
                    <label class="custom-file">
                      <input type="file" id="file-picker" class="custom-file-input" name="filestream" accept="image/*" multiple>
                      <label class="custom-file-label" for="file-picker">
                        Browse to attach images or drag them into the comment field
                      </label>
                    </label>
                    <div id="progress" class="progress hidden height-22p">
                      <div id="progress-bar" class="progress-bar height-22p">0%</div>
                    </div>
                </div>
              </div>
              <div class="card-footer bg-light">
                <div class="d-flex align-items-center">
                  <small>Comments use <a href="https://docs.pagure.org/pagure/usage/markdown.html"
                     target="_blank" rel="noopener noreferrer" class="notblue">Markdown Syntax</a></small>
                  <div class="ml-auto form-check pt-2 mr-3" title="Private issue?">
                          {{ form.private(class_="form-check-input") }}
                          <label class="form-check-label pl-2" for="private">Private</label>
                  </div>
                  <div>
                    <div class="btn-group">
                      {% if not type or type == 'new' %}
                      <input type="submit" class="btn btn-primary" value="Create Issue" tabindex=3>
                      {% elif type and type == 'edit' %}
                      <input type="submit" class="btn btn-primary" value="Update Issue #{{issue.id}}" tabindex=4>
                      {% endif %}
                    </div>
                  </div>
                </div>
              </div>
        </div>
      </div>
  </div>

  {% if (g.repo_user or open_access) and not type or type == 'new' %}
  <div class="col-md-4">
    <div class="mb-4">
        <h5 class="d-flex align-items-center font-weight-bold border-bottom mb-4">
          <div class="py-2 text-uppercase font-size-09">Metadata</div>
        </h5>

        <fieldset class="form-group">
            <label class="mb-1 pl-1"> <i class="fa fa-fw fa-user-plus"></i> <strong>Assignee</strong></label>
            <input class="form-control" name="assignee" id="assignee"
              placeholder="username"
              value="{{ request.form.assignee or '' }}" />
        </fieldset>

        <fieldset class="form-group">
           <label class="mb-1 pl-1"> <i class="fa fa-fw fa-tag"></i> <strong>Tags</strong></label>
           <input id="tag" class="form-control" type="text"
              placeholder="tag1, tag2" name="tag"
              title="comma separated list of tags"
              value="{{ request.form.tags or '' }}" />
        </fieldset>

        {% if repo.priorities %}
        <fieldset class="form-group">
            <label class="mb-1 pl-1"> <i class="fa fa-fw fa-bolt"></i> <strong>Priority</strong></label>
            {{form.priority}}
         </fieldset>
        {% endif %}

        {% if repo.milestones %}
        <fieldset class="form-group">
            <label class="mb-1 pl-1"> <i class="fa fa-fw fa-map-signs"></i> <strong>Milestone</strong></label>
            {{form.milestone}}
         </fieldset>
        {% endif %}
    </div>
  </div>
  {% endif %}
  </div>
  </form>
{% endblock %}

{% block jscripts %}
{{ super() }}
<script type="text/javascript" nonce="{{ g.nonce }}" src="{{
  url_for('static', filename='vendor/jquery.textcomplete/jquery.textcomplete.min.js') }}?version={{ g.version}}"></script>
<script type="text/javascript" nonce="{{ g.nonce }}" src="{{
  url_for('static', filename='vendor/emojione/emojione.min.js') }}?version={{ g.version}}"></script>
<script type="text/javascript" nonce="{{ g.nonce }}" src="{{
  url_for('static', filename='emoji/emojicomplete.js') }}?version={{ g.version}}"></script>
<script type="text/javascript" nonce="{{ g.nonce }}" src="{{
  url_for('static', filename='vendor/jquery.caret/jquery.caret.min.js') }}?version={{ g.version}}"></script>
<script type="text/javascript" nonce="{{ g.nonce }}" src="{{
  url_for('static', filename='vendor/jquery.atwho/jquery.atwho.min.js') }}?version={{ g.version}}"></script>
<script type="text/javascript" nonce="{{ g.nonce }}" src="{{
  url_for('static', filename='vendor/selectize/selectize.min.js') }}?version={{ g.version}}"></script>

<script type="text/javascript" nonce="{{ g.nonce }}">
{% if g.authenticated and form %}
$(document).ready(function() {
  // Set up the handler for the file input box.
  $("#file-picker").on("change", function(evt) {
    var files = evt.target.files;
    //doUpload("{{ form.csrf_token.current_token }}", this.files);
    var _txt = $("#issue_content").val();
    if (_txt) {
      _txt += '\n';
    }
    $("#issue_content").val(_txt + '<!!image>\n'.repeat(files.length));
  });

  // List username in @ drop-down
  $.get("{{ url_for('api_ns.api_users') }}", {
    pattern: '*'
  }).done(function(resp) {
    var userConfig = {
      at: '@',
      data: resp['mention'],
      insertTpl: '@${username}',
      displayTpl: "<li><img src=\"${image}\"> ${username} <small>${name}</small></li>",
      searchKey: "username"
    }
    $("#issue_content").atwho(userConfig);
  });

  var emojiStrategy;
  $.getJSON(
    '{{ url_for("static", filename="vendor/emojione/emoji_strategy.json") }}?version={{ g.version}}',
    function( data ) {
      emojiStrategy =  data;
    }
  );

  var folder = '{{url_for("static", filename="emoji/png/") }}?version={{ g.version}}';
  var json_url = '{{ url_for("static", filename="vendor/emojione/emoji_strategy.json") }}?version={{ g.version}}';
  emoji_complete(json_url, folder);

  $(".issue-template").on("click", function() {
    if ( !confirm('Do you want to load the new template?')){
      return false;
    }

    var _type = $( this ).attr('data-value');
    var _url = "{{
      url_for('internal_ns.get_ticket_template',
              repo=repo.name,
              username=repo.user.user if repo.is_fork else None,
              namespace=repo.namespace) }}";
    _url += '?template=' + _type;
    $.ajax({
      url: _url ,
      type: 'POST',
      data: {
        csrf_token: "{{ g.confirmationform.csrf_token.current_token }}",
      },
      dataType: 'json',
      success: function(res) {
        $("#issue_content").val(res.message);
      },
      error: function(res) {
        alert('Unable to get this template');
      }
    });
  });

  {% if (g.repo_user or open_access) %}
  var available_tags = [];
  {% for tog in tag_list %}
    available_tags.push("{{ tog.tag }}");
  {% endfor %}
  var items = available_tags.map(function(x) { return { item: x }; });

  $('#tag').selectize({
    delimiter: ',',
    options: items,
    persist: false,
    create: false,
    labelField: "item",
    valueField: "item",
    searchField: ["item"],
  });

  $("#priority").selectize({
    create: true
    });
  $("#milestone").selectize();
  {% endif %}

});

{% endif %}

$(function() {
  $( "#preview" ).hide();

  $( "#previewinmarkdown" ).click(
    function(event, ui) {
        var _text = $( "#issue_content" ).val();
        var _url = "{{ url_for('ui_ns.markdown_preview',
                        repo=repo.name,
                        user=repo.user.user if repo.is_fork,
                        namespace=repo.namespace) | safe}}";
        $.ajax({
          url: _url ,
          type: 'POST',
          data: {
            content: _text,
            csrf_token: "{{ g.confirmationform.csrf_token.current_token }}",
          },
          dataType: 'html',
          success: function(res) {
            var preview = emojione.toImage(res);
            $( "#preview" ).html(preview);
            $( "#previewinmarkdown" ).addClass("active");
            $( "#editinmarkdown" ).removeClass("active");
            $( "#issue_content" ).hide();
            $( "#preview" ).show();
          },
          error: function() {
            alert('Unable to generate preview!'+error);
          }
        });
        return false;
    }
  );

  $( "#editinmarkdown" ).click(
    function(event, ui) {
      $( "#editinmarkdown" ).addClass("active");
      $( "#previewinmarkdown" ).removeClass("active");
      $( "#issue_content" ).show();
      $( "#preview" ).hide();
    }
  );
});
</script>
{% endblock %}
