<!--
  -- Copyright (c) 2021, Alexander Helmboldt
  --
  --
  -- This file incorporates work covered by the following copyright and  
  -- permission notice:
  --
  -- Copyright (c) Bojan Mihelac and individual contributors.
  -- All rights reserved.
  --
  -- Redistribution and use in source and binary forms, with or without modification,
  -- are permitted provided that the following conditions are met:
  --
  --     1. Redistributions of source code must retain the above copyright notice,
  --        this list of conditions and the following disclaimer.
  --
  --     2. Redistributions in binary form must reproduce the above copyright
  --        notice, this list of conditions and the following disclaimer in the
  --        documentation and/or other materials provided with the distribution.
  --
  -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  -- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  -- DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
  -- ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
  -- ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  -->

{% extends "admin/import_export/base.html" %}
{% load i18n %}
{% load admin_urls %}
{% load import_export_tags %}
{% load static %}

{% block extrastyle %}
  {{ block.super }}
  {# Load the original styling definitions from the django-import-export package #}
  <link rel="stylesheet" type="text/css" href="{% static 'import_export/import.css' %}" />
  {# Load custom styling definitions #}
  <link rel="stylesheet" type="text/css" href="{% static 'gsheets_import/css/sticky.css' %}" />
  <link rel="stylesheet" type="text/css" href="{% static 'gsheets_import/css/file_and_google.css' %}" />
{% endblock %}

{% block extrahead %}
  {{ block.super }}
  {# Load a custom script to dynamically size the preview table and produce sticky column headers #}
  <script type="module" src="{% static 'gsheets_import/js/sticky.js' %}"></script>
{% endblock %}

{% block breadcrumbs_last %}
{% trans "Import" %}
{% endblock %}

{% block content %}

  {% if confirm_form %}
    <form action="{% url opts|admin_urlname:"process_import" %}" method="POST">
      {% csrf_token %}
      {{ confirm_form.as_p }}
      <p>
        {% trans "Below is a preview of data to be imported. If you are satisfied with the results, click 'Confirm import'" %}
      </p>
      <div class="submit-row">
        <input type="submit" class="default" name="confirm" value="{% trans "Confirm import" %}">
      </div>
    </form>
  {% else %}
    <form action="" method="post" enctype="multipart/form-data">
      {% csrf_token %}

      <p>
        {% trans "This importer will import the following fields: " %}
        <code>{{ fields|join:", " }}</code>
      </p>

      {% if import_example_sheet_link %}
        <p>
          An example Google Sheet with the correct format can be found <a href="{{ import_example_sheet_link }}" target="_blank">here</a>.
        </p>
      {% endif %}

      <fieldset class="module aligned">
        {% for field in form %}
          <div class="form-row">
            {{ field.errors }}

            {{ field.label_tag }}

            {{ field }}

            {% if field.field.help_text %}
            <p class="help">{{ field.field.help_text|safe }}</p>
            {% endif %}
          </div>
        {% endfor %}
      </fieldset>

      <div class="submit-row">
        <input type="submit" class="default" value="{% trans "Submit" %}">
      </div>
    </form>
  {% endif %}

  {% if result %}

    {% if result.has_errors %}

      <h2>{% trans "Errors" %}</h2>
      <ul>
        {% for error in result.base_errors  %}
        <li>
          {{ error.error }}
          <div class="traceback">{{ error.traceback|linebreaks }}</div>
        </li>
        {% endfor %}
        {% for line, errors in result.row_errors %}
          {% for error in errors %}
            <li>
              {% trans "Line number" %}: {{ line }} - {{ error.error }}
              <div><code>{{ error.row.values|join:", " }}</code></div>
              <div class="traceback">{{ error.traceback|linebreaks }}</div>
            </li>
          {% endfor %}
        {% endfor %}
      </ul>

    {% elif result.has_validation_errors %}

      <h2>{% trans "Some rows failed to validate" %}</h2>
        
      <p>{% trans "Please correct these errors in your data where possible, then reupload it using the form above." %}</p>
      
      <table class="import-preview">
        <thead>
          <tr>
            <th>{% trans "Row" %}</th>
            <th>{% trans "Errors" %}</th>
            {% for field in result.diff_headers %}
              <th>{{ field }}</th>
            {% endfor %}
          </tr>
        </thead>
        <tbody>
        {% for row in result.invalid_rows %}
          <tr>
            <td>{{ row.number }} </td>
            <td class="errors">
              <span class="validation-error-count">{{ row.error_count }}</span> 
              <div class="validation-error-container">
                <ul class="validation-error-list">
                  {% for field_name, error_list in row.field_specific_errors.items %}
                    <li>
                        <span class="validation-error-field-label">{{ field_name }}</span>
                        <ul>
                          {% for error in error_list %}
                            <li>{{ error }}</li>
                          {% endfor %}
                        </ul>
                    </li>
                  {% endfor %}
                  {% if row.non_field_specific_errors %}
                    <li>
                      <span class="validation-error-field-label">{% trans "Non field specific" %}</span>
                      <ul>
                        {% for error in row.non_field_specific_errors %}
                          <li>{{ error }}</li>
                        {% endfor %}
                      </ul>
                    </li>
                  {% endif %}
                </ul>
              </div>
            </td>
            {% for field in row.values %}
              <td>{{ field }}</td>
            {% endfor %}
          </tr>
        {% endfor %}
        </tbody>
      </table>
  
    {% else %}

      <h2>{% trans "Preview" %}</h2>

      <!-- Added the following div in order to implement consistent table overflow. -->
      <div class="results" id="no-error-container">

      <table class="import-preview" id="no-error-table">
        <thead>
          <tr>
            <th></th>
            {% for field in result.diff_headers %}
              <th>{{ field }}</th>
            {% endfor %}
          </tr>
        </thead>
        {% for row in result.valid_rows %}
          <tr class="{{ row.import_type }}">
            <td class="import-type">
              {% if row.import_type == 'new' %}
                {% trans "New" %}
              {% elif row.import_type == 'skip' %}
                {% trans "Skipped" %}
              {% elif row.import_type == 'delete' %}
                {% trans "Delete" %}
              {% elif row.import_type == 'update' %}
                {% trans "Update" %}
              {% endif %}
            </td>
            {% for field in row.diff %}
              <td>{{ field }}</td>
            {% endfor %}
          </tr>
        {% endfor %}
      </table>

      </div>

    {% endif %}

  {% endif %}

{% endblock %}


{% block footer %}

    {{ block.super }}

    {% if not confirm_form %}
        {# Load JavaScript's Google API and a custom script to handle the import of Google Sheets #}
        <script>
            const developerKey = '{{ gsheets_import_api_key }}';
            const clientId = '{{ gsheets_import_client_id }}';
            const appId = '{{ gsheets_import_app_id }}';
            const gsFormatDisplayName = '{{ gs_format_display_name }}';
            const dummyChoiceTxt = '{{ dummy_choice_txt }}';
        </script>
        <script type="text/javascript" src="{% static 'gsheets_import/js/import_gs.js' %}"></script>
        <script async defer src="https://apis.google.com/js/api.js"
              onload="this.onload = function() {}; loadLibraries()"
              onreadystatechange="if(this.readyState === 'complete') this.onload()">
        </script>
    {% endif %}

{% endblock %}
