import Vue from "vue";
import Browser from "../modules/browser";
import moment from "moment";

const LOCAL_STORAGE_KEY = "smartModalLastSavedDate";
const LOG_PREFIX = "[SmartModal]";

export default Vue.extend({

  data()
  {
    return {
      isClosing: false,
      isVisible: false,
    };
  },
  beforeMount()
  {
    /*
     * Device type check
     */

    const devicesTypesString = this.$el.dataset.devicesTypes;

    if (devicesTypesString === undefined)
    {
      console.info(`${LOG_PREFIX} no device type specified. Keeping the modal hidden...`);
      return;
    }

    const devicesTypes = devicesTypesString
      .split(",")
      .map(x => x.trim());

    const currentDevice = Browser.getCurrentDevice();

    if (currentDevice === null || devicesTypes.indexOf(currentDevice.type) === -1)
    {
      console.info(`${LOG_PREFIX} current device type '${currentDevice.type}' has been ignored since it's not in the devices types list defined as '${devicesTypesString}'. Keeping the modal hidden...`);
      return;
    }

    /*
     * Hours delay check
     */

    const hoursDelayString = this.$el.dataset.hoursDelay;
    const hoursDelay = parseInt(hoursDelayString, 10);

    if (isNaN(hoursDelay))
    {
      console.error(`${LOG_PREFIX} invalid value in data-hours-delay attribute. Expected integer, defined '${hoursDelayString}'`);
      return;
    }

    const currentDate = new Date();
    const lastSavedDate = this.getLastSavedDate();

    if (lastSavedDate === undefined)
    {
      console.info(`${LOG_PREFIX} no previously saved date found, saving the current date...`);
      this.isVisible = true;
      this.saveDate(currentDate);
      return;
    }

    const hoursDiff = moment(currentDate).diff(moment(lastSavedDate), 'hours');

    if (hoursDiff < hoursDelay)
    {
      console.info(`${LOG_PREFIX} hours difference (${hoursDiff} hours) below limit of ${hoursDelay} hours. Keeping the modal hidden...`);
      return;
    }
    console.info(`${LOG_PREFIX} hours difference (${hoursDiff} hours) is greater or equal than the limit of ${hoursDelay} hours. Saving new date time before display logic...`);
    this.saveDate(currentDate);
  },
  mounted()
  {
    if (this.isVisible)
    {
      document.body.dispatchEvent(new Event("scroll-disabled"));
    }
  },
  methods: {

    close()
    {
      this.isClosing = true;

      document.body.dispatchEvent(new Event("scroll-enabled"));

      const timeoutId = setTimeout(() => {

        clearTimeout(timeoutId);
        this.isVisible = false;

      }, 600);
    },
    getLastSavedDate()
    {
      if (!Browser.hasLocalStorage())
      {
        return undefined;
      }

      const lastSavedDate = window.localStorage.getItem(LOCAL_STORAGE_KEY);

      return lastSavedDate !== null ? new Date(lastSavedDate) : undefined;
    },
    saveDate(date)
    {
      window.localStorage.setItem(LOCAL_STORAGE_KEY, date.toISOString());
    }
  }
});
