import { InobyModule } from "@lib/inoby-module";
import * as $ from "jquery";

declare interface inobyWindow extends Window {
  inoby: any;
}

declare let window: inobyWindow;

export default class CookieBar extends InobyModule {
  private _animationSpeed = 200;

  run() {
    this.hookSettingsClick();
  }

  hookSettingsClick() {
    this.hideSettings();
    this.collapseSections();
    this.hookExpandSections();
    this.hookCheckboxes();

    $("#cookie-consent .btn-settings").on("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      this.showSettings();
    });

    $("#cookie-consent .btn-save").on("click", (e) => {
      this.saveSettings(true);
    });
  }

  showSettings() {
    $("#cookie-consent .btn-settings").hide();
    $("#cookie-consent .content").slideUp(this._animationSpeed);

    $("#cookie-consent .settings").slideDown(this._animationSpeed);
    $("#cookie-consent .btn-save").show();
  }

  hideSettings() {
    $("#cookie-consent .btn-settings").show();
    $("#cookie-consent .content").slideDown(this._animationSpeed);

    $("#cookie-consent .settings").slideUp(this._animationSpeed);
    $("#cookie-consent .btn-save").hide();
  }

  saveSettings(hide: boolean = false) {
    $("#cookie-settings .checkbox-buttons").trigger("option.change");
    if (hide) {
      $("#cookie-consent").hide();
    }
  }

  hookExpandSections() {
    $("#cookie-settings .section .title").on("click", (e) => {
      var $desc = $(e.target).siblings(".desc");
      var expanded = $desc.is(":visible");

      var $next_element = $(e.target).siblings(".arrow");
      var $other_elements = $("#cookie-consent .checkbox .arrow");

      if ($other_elements.hasClass("up")) {
        $other_elements.removeClass("up");
      }

      this.collapseSections();
      if (!expanded) {
        $desc.slideToggle(this._animationSpeed);
        $next_element.toggleClass("up");
      }
    });
  }

  hookCheckboxes() {
    $("#cookie-settings input[type=checkbox]").on("change", (e) => {
      var $check = $(e.target);
      var $hidden = $("#cookie-settings input[type=hidden][name=" + $check.prop("name") + "]");
      if ($check.is(":checked")) {
        $hidden.val("1");
      } else {
        $hidden.val("0");
      }
    });
  }

  collapseSections() {
    $("#cookie-settings .section .desc").slideUp(this._animationSpeed);
  }
}

new CookieBar().runOnReady();
