{% load i18n %}
{% load static %}

{% load unicms_contexts %}
{% load unicms_pages %}
{% load unicms_publications %}

<div class="row">
    <div class="col-4">
            <div class="card-wrapper card-space  pb-0">
            <div class="card card-bg no-after">
                <div class="card-body">
        <h4 class="card-title mb-0" style="">
            {% trans "Search" %} in Unical
        </h4>
        </div>
        </div>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div class="card-wrapper card-space">
            <div class="card card-bg no-after">
                <br>
                <div class="card-body">
                    <div class="form-group">
                      <div class="input-group">
                          <label for="search">{% trans 'Write words and "phrases" that you are looking for' %}</label>
                          <input type="text" class="form-control" id="search" name="search">
                          <div class="input-group-append">
                              <div class="input-group-text">
                                  <svg class="icon icon-sm icon-muted"><use xlink:href="{% static 'svg/sprite.svg' %}#it-search"></use></svg>
                              </div>
                            <button class="btn btn-primary" type="button" id="search-button" onclick="search.get_args=encodeQueryData(get_form_paramenters());">
                                {% trans "Search" %}</button>
                          </div>
                        </div>
                    </div>

                    <div id="collapseDiv1" class="collapse-div" role="tablist">
                      <div class="collapse-header" id="heading1">
                        <button style="padding: 0px; color: #19191a;" data-toggle="collapse" data-target="#collapse1" aria-expanded="false" aria-controls="collapse1">
                          {% trans "Ricerca Avanzata" %}
                        </button>
                      </div>

                      <div id="collapse1" class="collapse" role="tabpanel" aria-labelledby="heading1">
                        <br>
                        <div class="collapse-body" style="padding: 0px;">

                            <!-- Date picker -->
                            <div class="it-datepicker-wrapper">
                              <div class="form-group">

                                  <div class="row">
                                    <div class="col-sm">
                                        <label for="date_from"></label>
                                        <input class="form-control it-date-datepicker"
                                               id="date_from" type="text" placeholder="{% trans 'Dalla data publicazione' %}">
                                    </div>
                                    <div class="col-sm">
                                        <label for="date_to"></label>
                                        <input class="form-control it-date-datepicker"
                                               id="date_to" type="text" placeholder="{% trans 'Alla data di publicazione' %}">
                                    </div>
                                  </div>

                              </div>
                            </div>

                          <!-- Categories -->
                          <div class="form-group">
                          <div class="row">
                            <div class="col-sm">
                                <div class="bootstrap-select-wrapper">
                                  <label for="categories_input">{% trans "Categoria" %}</label>
                                  <select id="categories_input" multiple="true" data-multiple-separator="">
                                    {% cms_categories as categories %}
                                    {% for cat in categories %}
                                    <option value="{{ cat }}" title="" placeholder="" data-content="<span class='select-pill'><span class='select-pill-text'>{{ cat }}</span></span>"></option>
                                    {% endfor %}
                                  </select>
                                </div>
                              </div>
                          </div>
                          </div>

                          <!-- web site -->
                          <div class="form-group">
                          <div class="row">
                            <div class="col-sm">
                                <div class="bootstrap-select-wrapper">
                                  <label for="websites_input">{% trans "Web Site" %}</label>
                                  <select id="websites_input" multiple="true" data-multiple-separator="">
                                    {% cms_sites as sites %}
                                    {% for site, domain in sites %}
                                    <option value="{{ domain }}" title="" placeholder="" data-content="<span class='select-pill'><span class='select-pill-text'>{{ domain }}</span></span>"></option>
                                    {% endfor %}
                                  </select>
                                </div>
                            </div>
                          </div>
                          </div>

                        </div>
                      </div>
                    </div>

                </div>
            </div>
        </div>
    </div>
</div>

<div class="row" id="results">
</div>

<script>

window.onload = function() {
  // inline arg load from url
  let queryString = window.location.search
  let urlParams = new URLSearchParams(queryString);
  let search = urlParams.get('search')
  if (search) {
    document.getElementById("search").value = search;
    document.getElementById("search-button").click()
  }
};

function get_form_paramenters(){
    let dict = {};

    // search
    let search = document.getElementById('search').value
    if (search) dict['search'] = search

    // categories
    let cat_placeholder = jQuery.fn.selectpicker.defaults['noneSelectedText'] // document.getElementById('categories_input').dataset.placeholder
    let cat_obj = document.querySelectorAll("[data-id='categories_input']")[0]
    let categories = cat_obj.innerText.trim().split('\n').filter(function(e) { return e !== cat_placeholder })
    dict['categories'] = categories.join(',')

    // date_from
    let date_from = document.getElementById('date_from').value
    if (date_from) {
        date_from = date_from.split('/')
        dict['date_start'] = date_from[2]+'-'+date_from[1]+'-'+date_from[0]
    }
    // date_to
    let date_to = document.getElementById('date_to').value
    if (date_to) {
        date_to = date_to.split('/')
        dict['date_end'] = date_to[2]+'-'+date_to[1]+'-'+date_to[0]
    }
    // websites
    let site_placeholder = jQuery.fn.selectpicker.defaults['noneSelectedText'] //document.getElementById('websites_input').dataset.placeholder
    let site_obj = document.querySelectorAll("[data-id='websites_input']")[0]
    let sites = site_obj.innerText.trim().split('\n').filter(function(e) { return e !== site_placeholder })
    if (sites.length > 0) dict['sites'] = sites.join(',')

    return dict
}

function encodeQueryData(data) {
   const ret = [];
   for (let d in data)
     ret.push(encodeURIComponent(d) + '=' + encodeURIComponent(data[d]));
   return '?'+ret.join('&');
}

Vue.component('list-panel', {
  props: {
      data: Array,
    },
  template: `
    <div class="card-wrapper card-space" >
        <div class="card card-bg no-after">
          <div class="card-body py-1">

            <div class="row">
                <div class="col w-50">
                    <span style="color:#050b12;">
                        <b>[[ data.count || 0]] {% trans "results" %}</b> in <b>[[ data.total_pages || 0 ]] {% trans "pages" %}</b>
                    </span>
                </div>

                <div class="col w-50 ">
                  <div class="float-right">
                  <span>
                      <a class="" style="color:#050b12;" v-if="data.page_number > 1" @click="search.prevPage()">
                          <span class="sr-only"> {% trans "Page" %} </span> &lt; <small>{% trans "Previous" %}</small>
                      </a>
                  </span>

                  <span class="mr-2 ml-2" >[[ data.page_number ]] / <b>[[ data.total_pages ]]</b></span>
                      <a class="" style="color:#050b12;" @click="search.nextPage()" v-if="data.page_number < data.total_pages">
                          <span class="sr-only"><small>{% trans "Page" %} </span>{% trans "Next" %} &gt;</small>
                      </a>
                  </div>
                </div>
            </div>

          </div>
        </div>
    </div>
  `
})

var search = new Vue({
  el: '#results',
  template: `
    <div v-if="newsLoaded == false">
      {% include "loading-jumbo.html" %}
    <div v-else>
         <div class="" v-if="items">

            <list-panel v-bind:data="items" v-if="items.results"></list-panel>

            <!--start card-->
            <div class="card-wrapper card-space"  v-for="item in items.results" :key="item.id">
                <div class="card card-bg no-after">
                    <div class="card-body">

                        <div class="row" v-if="item.heading">
                            <div class="col-3">
                                <!-- image preview -->
                                 <div style="width: 100%" class="img-responsive-wrapper mb-1" v-if="item.image">
                                    <div class="img-responsive mt-2">
                                        <figure class="img-wrapper">
                                            <img  v-bind:src="item.image" />
                                        </figure>
                                    </div>
                                </div>
                                <!-- end image -->
                            </div>
                            <div class="col-lg">
                                <div class="etichetta mb-0" style="text-transform: none;">
                                    <span v-for="(cat, index) in item.categories">
                                        <span v-if="index>0">&nbsp;&middot</span>
                                            <small class="text-muted">[[ cat | capitalize ]]</small>
                                    </span>
                                </div>
        <!--
                                <span class="small text-muted mb-2">[[ item.indexed|formatDate ]]</span>
        -->
                                <p><b>[[ item.title ]]</b></p>
                                <p>[[ item.heading | truncate(448) ]]</p>
                            </div>
                        </div>
<!--
                        <h6>{% trans "Published in" %}</h6>
-->
                        <div class="mt-2">
                          <ul class="list-unstyled">
                            <li v-for="url in item.urls">
                              <a style="text-decoration: none; color: #17324d;" v-bind:href="[[ url ]]">
                                <div class="it-right-zone">
                                  <svg class="icon icon-xs">
                                    <use xlink:href="{% static 'svg/sprite.svg' %}#it-chevron-right"></use>
                                  </svg>
                                  <span class="text">//[[ url | val_replace('//', '') ]]</span>
                                </div>
                              </a>
                            </li>
                          </ul>
                        </div>

                        <div v-if="item.translations && item.translations.length >= 1">
                            <h6>{% trans "Available in" %}</h6>
                            <span v-for="(trans, index) in item.translations"">
                                <span v-if="index>0">&nbsp;&middot</span>
                                    [[ trans.language ]]
                            </span>

                        </div>

                    </div>

                </div>
            </div>
            <!--end card-->

            <list-panel v-bind:data="items" v-if="items.results"></list-panel>

        </div>
    </div>
    `,
  data () {
    return {
      items: [],
      newsLoaded: true,
      get_args: '',
      url: '{% url "unicms_search:api-search-engine" %}'
    }
  },

 watch: {
    get_args: function (val) {
      this.CallURL()
    }
  },

  mounted () {
      window.addEventListener("keypress", function(e) {
      // console.log(e.keyCode);
      if (e.keyCode == 13) {
        search.update_args();
      }
    });
    },

  beforeMount () {
  },
  methods: {
    CallURL () {
        this.newsLoaded = false;
        axios
          .get( this.url + this.get_args)
          .then(response => (this.items = response.data))
          .then(response => (this.newsLoaded = true))
          .then(response => (this.scrollToTop()))
      },
    scrollToTop () {
        // faulty on mobile ...
        window.scrollTo({top:420, left:0, behavior: 'smooth'});
        },
    update_args (values) {
        let base_args = encodeQueryData(get_form_paramenters());
        if (values) base_args += values
        this.get_args = base_args;
        },
    nextPage () {
        let num = this.items.page_number + 1;
        let sep = '';
        if (this.get_args) sep = '&'
        this.update_args(sep + 'page_number=' + num);
        },
    prevPage () {
        let num = this.items.page_number - 1;
        let sep = '';
        if (this.get_args) sep = '&'
        this.update_args(sep + 'page_number=' + num);
        },

    }
})
</script>
</script>


