import $ from 'jquery';
import Cookies from 'js-cookie';

// const Typeahead = require("typeahead.js/dist/typeahead.jquery.js");

class IHKSwitch {
  constructor(section) {
    const t = this;
    this.serviceUrlBase = "/blueprint/servlet/serviceport/ihkfinder";
    this.ihklListUrl = this.serviceUrlBase + "/ihk/all";
    this.communitiesUrl = this.serviceUrlBase + "/community/all";
    this.zipsUrl = this.serviceUrlBase + "/zip/";
    this.ihkList = null;
    this.nearestIhk = null;
    this.formLocked = false;

    section.addClass("initialized");
    t.section = section;
    t.form = section.find(".ihk-finder");

    this.landingChangerBtn = $('.ihk-landing-changer');
    if (this.landingChangerBtn.length) {
      this.landingChangerBtn.on("click", (e) => {
        e.preventDefault();
        // lösche cookie so dass der User die Möglichkeit hat auf die neue IHK zu wechseln (Mit cookie wird es es nur weitergeleitet)
        Cookies.remove('my-ihk', {expires: 365});
        // clear session cookie just in case
        if (window.sessionStorage && window.sessionStorage.getItem("my-ihk-ignore") === "true") {
          window.sessionStorage.removeItem("my-ihk-ignore");
        }

        window.location = "/";
      })
    }

    this.checkState();
    this.initClosing()
    this.initStayHereZipBtn(section);
  }

  initStayHereZipBtn(section) {
    let stayHereBtn = section.find('button.stay-here-zip');
    if (stayHereBtn) {
      stayHereBtn.on('click', (e) => {
        e.preventDefault();
        this.getCurrentIhkAndSetCookie(true);
      });
    }
  }

  isSessionStorageKeySet() {
    try {
      if (window.sessionStorage && window.sessionStorage.getItem("my-ihk-ignore") === "true") {
        return true;
      }
    } catch (e) {
      console.info("Something is wrong with session cookie", e)
    }
    return false;
  }

  initClosing() {
    this.section.find('.closer').on('click', () => {
      this.setSessionStorageCookie();
      this.hideSwitch();
    });
  }

  hideSwitch() {
    this.section.addClass('hide');
    setTimeout(() => {
      this.section.removeAttr('data-show-step');
    }, 400);
  }

  checkState() {
    if (this.isSessionStorageKeySet()) {
      return;
    }
    const cookie = Cookies.get('my-ihk');

    if (cookie) {
      this.initSwitch();
    } else {
      this.initSetCurrentIHK();
    }
  }

  initTypeahead() {
    const t = this;
    var src = {
      name: 'communities',
      displayKey: 'name',
      source: function (query, syncResults, asyncResults) {
        return $.getJSON(t.zipsUrl + query, function (response) {
          console.log(response);

          if (response.jsonResponse && response.status === 200) {
            if (response.jsonResponse.length > 0) {
              return asyncResults(response.jsonResponse);
            }
          }

          return asyncResults([]);
        });
      },
      templates: {
        empty: ['<p class="no-result">Leider nichts gefunden</p>'].join('\n'),
        suggestion: function (e) {
          return ('<div data-id="' + e.ihknr + '" ><span class="name">' + e.name + '</span/><span class="zip">' + (e.zips ? e.zips.join(', ') : ' ') + '</span></div>');
        }
      }
    }

    t.zipInput = t.form.find('#zipSwitchInput');

    t.zipInput.typeahead({
        highlight: true,
        ttl_ms: 0,
        minLength: 5,
      },
      src
    );

    t.zipInput.bind('typeahead:selected', (e, item, sourceName) => {
      if (item) {
        if (!t.myLocation) {
          t.myLocation = {}
        }
        t.setMyLocationAsObj(item);
        t.setCookie();
        t.initSuccess();
      }
    });

    t.form.on('mouseenter', '.tt-suggestion', function () {
      $('.marker#ihk-' + $(this).attr('data-id')).addClass('hover').siblings('hover').removeClass('hover');
    })

    t.form.on('mouseleave', '.tt-suggestion', function () {
      $('.marker#ihk-' + $(this).attr('data-id')).removeClass('hover');
    })
  }

  initForm() {
    this.section.attr('data-show-step', 'form');
    this.initTypeahead();
  }

  initSetCurrentIHK() {
    this.section.attr('data-show-step', 'form');

    this.section.find('.stay-here').on('click', () => {
      this.getCurrentIhkAndSetCookie(false);
      this.hideSwitch();
    });
    this.section.find('.set-session-cookie').on('click', () => {
      this.setSessionStorageCookie();
      this.hideSwitch();
    })
  }

  setMyLocationAsObj(item) {
    this.myLocation = {
      city: item.city,
      country: item.country,
      ihknr: item.ihknr,
      zip: item.zip,
      distance: item.distance || 0,
      geodata: item.geodata,
      homepage: item.homepage,
      key: item.key,
      longname: item.longname,
      name: item.name
    };
  }

  initSwitch() {
    let myIHK;
    const currIHK = parseInt(this.section.find('.current-ihk').attr('data-ihknr'));
    const myihkCookie = Cookies.get('my-ihk');
    if (this.myLocation && this.myLocation.ihknr && this.ihkList) {
      myIHK = this.ihkList.find(ihk => {
        return ihk.ihknr === this.myLocation.ihknr
      })
    } else if (myihkCookie) {
      myIHK = JSON.parse(myihkCookie);
      this.myLocation = myIHK;
    }

    if (myIHK && myIHK.ihknr && (currIHK !== myIHK.ihknr)) {
      this.section.find('.my-ihk').text(myIHK.longname);
      this.section.attr('data-show-step', 'switch');
    } else {
      this.hideSwitch();
    }

    this.section.find('.stay-here').on('click', () => {
      this.getCurrentIhkAndSetCookie(false);
      this.hideSwitch();

    });
    // this.section.find('.change-ihk').on('click', () => {
    //   this.initSuccess();
    // })
    this.section.find('.set-session-cookie').on('click', () => {
      this.setSessionStorageCookie();
      this.hideSwitch();
    })
  }

  setSessionStorageCookie() {
    try {
      window.sessionStorage.setItem("my-ihk-ignore", "true");
    } catch (e) {
      console.info("Unable to set session Storage cookie, ", e)
    }
  }

  getCurrentIhkAndSetCookie(withReload) {
    this.getIhkList().then(() => {
      let myIHK;
      const currIHK = parseInt(this.section.find('.current-ihk').attr('data-ihknr'));
      myIHK = this.ihkList.find(ihk => {
        return ihk.ihknr === currIHK
      });
      this.setMyLocationAsObj(myIHK);
      this.setCookie();
      if (withReload) {
        window.location.reload();
      }
    });

  }

  initSuccess() {
    this.section.attr('data-show-step', 'success');
    if (this.myLocation && this.myLocation.homepage) {
      setTimeout(() => {
        window.location = this.myLocation.homepage;
      }, 2000)
    }
  }

  initGeolocation() {
    const t = this;
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((pos) => {
        this.getIhkList(pos)
      }, (err) => {
        this.locationError(err)
      });
    }

    this.section.find('.change-location').on('click', () => {
      t.initForm();
    });
    this.section.find('.accept-location').on('click', () => {
      t.setCookie();
    });
    this.section.find('.toggle-location-info').on('click', (e) => {
      e.preventDefault();
      t.section.find('#location-info').slideToggle(250, 'swing');
    });
  }

  locationError() {
    this.section.attr('data-show-step', 'form');
    this.initForm();
  }

  setCookie() {
    try {
      if (this.myLocation) {
        Cookies.set('my-ihk', JSON.stringify(this.myLocation).toString(), {expires: 365});
        Cookies.set('ihknr', this.myLocation.ihknr, {expires: 365});
      }
    } catch (e) {
      console.log("Unable to set cookie");
    }
    this.initSwitch();
  }

  calculateDistance(ihk, currentPosition) {
    const p = 0.017453292519943295;
    const c = Math.cos;
    const a = 0.5 - c((ihk.latitude - currentPosition.latitude) * p) / 2 + c(currentPosition.latitude * p) * c(ihk.latitude * p) * (1 - c((ihk.longitude - currentPosition.longitude) * p)) / 2;
    return 12742 * Math.asin(Math.sqrt(a));
  }

  getIhkList(position) {
    return $.getJSON(this.ihklListUrl, (response) => {
      if (response.jsonResponse && response.status === 200) {
        this.ihkList = response.jsonResponse;
        if (position) {
          this.showGeolocationStep(position);
        }
      }
    })
  }

  showGeolocationStep(position) {
    const t = this;
    t.setNearestIhkFromJson(position);
    t.section.find('.my-location').text(t.nearestIhk.zip + ' ' + t.nearestIhk.city);
    t.setMyLocationAsObj(t.nearestIhk);
    t.section.find('.my-ihk').text('IHK ' + t.nearestIhk.name);
    t.section.attr('data-show-step', 'geolocation');
  }

  setNearestIhkFromJson(position) {
    const t = this;
    $.each(t.ihkList, function (index, ihk) {
      const distance = t.calculateDistance(ihk.geodata, position.coords);
      if (t.nearestIhk) {
        if (t.nearestIhk.distance > distance) {
          ihk.distance = distance;
          t.nearestIhk = ihk;
        }
      } else {
        ihk.distance = distance;
        t.nearestIhk = ihk;
      }
    });
  }
}

export default IHKSwitch;

$('body').on('ihk-init', () => {
  $('.ihk-switch:not(.initialized)').each((el) => {
    new IHKSwitch($(el));
  });
});
