{% 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 href="{{ url_for('static', filename='emoji/emojione.sprites.css') }}"
  rel="stylesheet" />
{% endblock %}


{% block repo %}
<div class="row">
  <div class="col-md-8 col-md-offset-2">
    <div class="card">
      <div class="card-header">
        {% if not type or type == 'new' %}
        New issue
        {% elif type and type == 'edit' %}
        Edit issue #{{ issueid }}
        {% endif %}
      </div>
      <div class="card-block">
        {% if not type or type == 'new' %}
          <form action="{{ url_for('.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('.edit_issue',
                repo=repo.name,
                username=username,
                namespace=repo.namespace,
                issueid=issueid) }}" method="post"
                enctype="multipart/form-data">
        {% endif %}
        {{ render_bootstrap_field(form.title, field_description="Gist of your issue") }}
        {% if type == 'edit' %}
            {{ render_bootstrap_field(form.status, field_description="bug status") }}
        {% endif %}
        {% if types %}
        <fieldset class="form-group  ">
          <strong><label for="status">Type</label></strong>
          <select class="form-control c-select" id="type" name="type">
            {% for type in types %}
            <option selected value="{{ type }}">{{ type }}</option>
            {% endfor %}
          </select>
          <div>
            <small class="text-muted">Ticket type</small>
          </div>
        </fieldset>
        {% endif %}
        {{ render_bootstrap_field(form.private, field_description="Do you want to keep the issue private?") }}
          <fieldset class="form-group">
            <label for="issue_content"><strong>Description</strong></label>
            <small class="text-muted pull-xs-right">
              <span class="btn btn-sm btn-secondary inactive"
                aria-pressed="false" id="previewinmarkdown">Preview</span>
            </small>
            <textarea class="form-control" rows="8" id="issue_content" name="issue_content"
                placeholder="Describe your issue">
              {%- if issue %}{{ issue.content }}{%
                  elif form.issue_content.data %}{{ form.issue_content.data }}{%
                  elif default %}{{ default }}{%
              endif -%}
            </textarea>
            <div>

              {% if form.issue_content.errors %}
              <span class="pull-xs-right text-danger">
                <small>
                {% for error in form.issue_content.errors %}
                  {{ error }}&nbsp;
                {% endfor %}
                </small>
              </span>
              {% endif %}
            </div>
            <div id="preview">
            </div>
          </fieldset>
        Attach file <input id="file-picker" type="file" name="filestream" accept="image/*" multiple>

        <p class="buttons indent">
          {% if not type or type == 'new' %}
          <input type="submit" class="btn btn-primary" value="Create">
          {% elif type and type == 'edit' %}
          <input type="submit" class="btn btn-primary" value="Update">
          {% endif %}
          <input type="button" value="Cancel" class="btn btn-secondary" onclick="history.back();">
          {{ form.csrf_token }}
          <a href="http://daringfireball.net/projects/markdown/syntax"
            target="_blank" rel="noopener noreferrer">Markdown Syntax</a>
        </p>
      </form>
      </div>
    </div>

    {% if authenticated and g.repo_admin and type and type == 'edit' %}
    <form method="post" class="pull-xs-right" action="{{
        url_for('.delete_issue',
                repo=repo.name,
                username=username,
                namespace=repo.namespace,
                issueid=issueid) }}">
      <button class="btn btn-danger" type="submit"
          onclick="return confirm('Are you sure to delete this ticket? \nThis is final and cannot be un-done.');"
          title="Delete this ticket">
        <span class="icon icon-trash blue"></span>
        Delete issue
      </button>
      {{ form.csrf_token }}
    </form>
    {% endif %}

  </div>
</div>

{% endblock %}

{% block jscripts %}
{{ super() }}
<script type="text/javascript"
    src="{{ url_for('static', filename='emoji/jquery.textcomplete.min.js') }}">
</script>
<script type="text/javascript"
    src="{{ url_for('static', filename='emoji/emojione.min.js') }}">
</script>
<script type="text/javascript"
    src="{{ url_for('static', filename='emoji/emojicomplete.js') }}">
</script>
<script type="text/javascript">
{% if authenticated and form %}
$(document).ready(function() {
  // Set up the handler for the file input box.
  $("#file-picker").on("change", function() {
    //doUpload("{{ form.csrf_token.current_token }}", this.files);
    var _txt = $("#issue_content").val();
    if (_txt) {
      _txt += '\n';
    }
    var _loc = "{{ url_for('view_issue_raw_file',
        repo=repo.name,
        username=username,
        namespace=repo.namespace,
        filename='') }}" + this.file;

    $("#issue_content").val(_txt + '<!!image>');
  });

  var emojiStrategy;
  $.getJSON(
    '{{ url_for("static", filename="emoji/emoji_strategy.json") }}',
    function( data ) {
      emojiStrategy =  data;
    }
  );

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

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

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

});

{% endif %}

$(function() {
  $( "#preview" ).hide();
  $( "#previewinmarkdown" ).click(
    function(event, ui) {
      if ($( "#previewinmarkdown" ).hasClass("inactive")){
        var _text = $( "#issue_content" ).val();
        var _url = "{{ url_for('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: "{{ form.csrf_token.current_token }}",
          },
          dataType: 'html',
          success: function(res) {
            var preview = emojione.toImage(res);
            $( "#preview" ).html(preview);
            $( "#previewinmarkdown" ).removeClass("inactive");
            $( "#previewinmarkdown" ).addClass("active");
            $( "#issue_content" ).hide();
            $( "#preview" ).show();
          },
          error: function() {
            alert('Unable to generate preview!'+error);
          }
        });
        return false;
      } else if ($( "#previewinmarkdown" ).hasClass("active")){
        $( "#previewinmarkdown" ).addClass("inactive");
        $( "#previewinmarkdown" ).removeClass("active");
        $( "#issue_content" ).show();
        $( "#preview" ).hide();
      }
    }
  );
});
</script>
{% endblock %}
