window.addEventListener('DOMContentLoaded', function (event) {
  const typeId = document.querySelector('#article-search').dataset.typeId;
  Vue.directive('click-outside', {
    bind: function (el, binding, vnode) {
      el.clickOutsideEvent = function (event) {
        // here I check that click was outside the el and his children
        if (!(el == event.target || el.contains(event.target))) {
          // and if it did, call method provided in attribute value
          vnode.context[binding.expression](event);
        }
      };
      document.body.addEventListener('click', el.clickOutsideEvent);
    },
    unbind: function (el) {
      document.body.removeEventListener('click', el.clickOutsideEvent);
    },
  });

  var search = new Vue({
    el: '.search-wrapper',
    data: {
      siteId: null,
      language: '',
      apiUrl: '',
      mode: '',
      search: '',
      searchVisible: false,
      articles: [],
      tags: [],
      featuredTags: [],
      featuredTagsLoaded: false,
      searchYield: false,
    },
    mounted() {
      this.searchContent(false).then((data) => {
        var urlTagID = this.getUrlParam('tagId');
        if (urlTagID) {
          var tagName = '';
          this.tags.forEach(function (item, index) {
            if (urlTagID == item.id) tagName = item.name;
          });

          if (tagName != '') {
            this.searchByTag(tagName, urlTagID);
          }
        }
      });
    },
    created() {
      this.language = document.getElementById('language').value;
      this.siteId = document.getElementById('siteId').value;
      this.apiUrl = document.getElementById('serverUrl').value;
      this.mode = document.getElementById('mode').value;
    },
    watch: {
      search: function (val) {
        // Start the search only when user enters 3 or more letters
        this.searchVisible = false;

        if (val == '') {
          this.searchContent(false);
        } else if (val.length >= 3 && !this.searchYield) {
          this.searchContent(true);
        } else {
          searchResults.$data.articles = [];
          searchResults.$data.tags = [];
          searchResults.$data.resultMessage = 'No results.';
        }

        this.searchYield = false;
      },

      articles: function (val) {
        this.totalPages = Math.ceil(val.length / 3);
        this.currentPage = 1;
        this.resultCount = val.length;
      },
    },

    methods: {
      fetchData: function () {
        return new Promise((resolve, reject) => {
          var url =
            this.apiUrl +
            'api/dynamic/' +
            'searchArticles?q=' +
            this.search +
            '&language=' +
            this.language +
            '&siteId=' +
            this.siteId +
            '&mode=' +
            this.mode +
            '&typeId=' +
            typeId;
          axios
            .get(url)
            .then((response) => {
              resolve(response.data);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },

      fetchDataTag: function (tagId) {
        return new Promise((resolve, reject) => {
          var url =
            this.apiUrl +
            'api/dynamic/' +
            'searchArticlesByTag?tagId=' +
            tagId +
            '&language=' +
            this.language +
            '&siteId=' +
            this.siteId +
            '&mode=' +
            this.mode +
            '&typeId=' +
            typeId;
          axios
            .get(url)
            .then((response) => {
              resolve(response.data);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },

      goTo: function (url) {
        document.location.href = url;
      },
      searchContent: function (showSearch) {
        return new Promise((resolve, reject) => {
          this.search = $('#article-search').val();
          this.fetchData()
            .then((data) => {
              if ((data.articles && data.articles.length != 0 ) || (data.tags && data.tags.length != 0)) {
                if (showSearch) this.searchVisible = true;

                // Hacky solution to get two VUE instances to communicate with each other with jquery.
                searchResults.$data.articles = data.articles;
                searchResults.$data.tags = data.tags;

                var searchText = '';

                if (this.search != '') {
                  searchText = '<br>"' + this.search + '"';
                }

                searchResults.$data.resultMessage =
                  'Search results' + searchText;
              } else {
                this.searchVisible = false;

                // Hacky solution to get two VUE instances to communicate with each other with jquery.
                searchResults.$data.articles = [];
                searchResults.$data.tags = [];
                searchResults.$data.resultMessage = 'No results.';
              }

              this.articles = data.articles;
              if (!showSearch && !this.featuredTagsLoaded) {
                this.featuredTagsLoaded = true;
                this.featuredTags = data.tags;
              }

              this.tags = data.tags;

              resolve(data);
            })
            .catch((error) => {
              reject(error);
            });
        });
      },

      searchContentTag: function (tagId) {
        this.search = $('#article-search').val();

        this.fetchDataTag(tagId)
          .then((data) => {
            if (data.articles.length != 0) {
              this.searchVisible = false;

              // Hacky solution to get two VUE instances to communicate with each other with jquery.
              searchResults.$data.articles = data.articles;
              var searchText = '';

              if (this.search != '') {
                searchText = '<br>"' + this.search + '"';
              }
              searchResults.$data.resultMessage = 'Search results' + searchText;
            } else {
              this.searchVisible = false;

              // Hacky solution to get two VUE instances to communicate with each other with jquery.
              searchResults.$data.articles = [];
              searchResults.$data.resultMessage = 'No results.';
            }

            this.articles = data.articles;

            // console.log(data);
          })
          .catch((error) => {
            // console.log(error);
          });
      },

      changeSearch: function () {},

      closeAutoComplete: function (event) {
        // do something - probably hide the dropdown menu / modal etc.
        this.searchVisible = false;
      },

      searchByTag: function (tagName, tagId) {
        this.searchYield = true;

        this.searchContentTag(tagId);
        this.searchVisible = false;
        this.search = tagName;
      },

      getUrlParam: function (name) {
        var results = new RegExp('[?&]' + name + '=([^&#]*)').exec(
          window.location.search
        );

        return results !== null ? results[1] || 0 : false;
      },
    },
  });

  var searchResults = new Vue({
    el: '.search-result',
    data: {
      resultJSON: null,
      articles: null,
      paginatedArticles: null,
      tags: null,
      resultMessage: 'No results.',
      totalPages: 0,
      currentPage: 0,
      resultCount: 0,
      itemsPerPage: 8,
    },
    mounted() {},
    created() {
        this.apiUrl = document.getElementById('serverUrl').value;
        this.siteId = document.getElementById('siteId').value;
    },
    watch: {
      articles: function (val) {
        this.resultCount = val.length;
        this.totalPages = Math.ceil(this.resultCount / this.itemsPerPage);
        this.currentPage = 0;
        this.paginatedArticles = this.paginate(val);
      },
      currentPage: function (val) {
        this.paginatedArticles = this.paginate(this.articles);
      },
    },
    methods: {
      goTo: function (url) {
        document.location.href = url;
      },
    addToBasket: function (id, name, checkout) {
       const data = {"siteId":this.siteId,"productId":id,"quantity":"1","orderId": getCookie('orderId') || 0 }
       axios.post(this.apiUrl + 'ecom/addToBasket', data).then(function(response){
        //!sessionStorage.getItem('orderId') && sessionStorage.setItem('orderId', response.data.id)
        !getCookie('orderId') && setCookie('orderId', response.data.id, 1)
        basketProducts.updateBasket(response.data, name)
        if(checkout) goToCheckout()
       })

      },  
      setPage: function (number) {
        this.currentPage = number;
      },

      paginate: function (list) {
        if (list !== null) {
          this.resultCount = list.length;
          if (this.currentPage >= this.totalPages) {
            this.currentPage = this.totalPages - 1;
          }
          var index = this.currentPage * this.itemsPerPage;
          return list.slice(index, index + this.itemsPerPage);
        } else {
          return null;
        }
      },
    },

    computed: {},
  });
});