interface SetValue {
  data: any;
  time: number;
}

let storage = {
  /**
   * The get method retrieves a value from the storage.
   * @param {string} key  The key identifier of data to get
   * @returns The current value associated with the given key, or null if the given key does not exist in the list associated with the object.
   */
  get(key: string): any {
    if (!key) {
      console.error("Key is missing");
      return null;
    }

    if (!window.sessionStorage.getItem(key)) return null;

    try {
      const values: SetValue = JSON.parse(window.sessionStorage.getItem(key));
      // We return data if the exist in the storage object
      if (values?.data) 

        return values.data;
      
    } catch (e) {
      // On error we will remove the key from the storage
      // And return null
      this.remove(key);
    }
    return null;
  },

  /**
   * Sets the value of the pair identified by key to value,
   * creating a new key/value pair if none existed for key previously.
   * @param {string} key The key identifier of data to set
   * @param {any} value The value to store
   * @returns The value if set, or null if not set
   */
  set(key: string, value: any): any {
    if (!value || value == {} || (Array.isArray(value) && !value.length)) {
      this.remove(key);
      return null;
    }

    const now = new Date().getTime();

    let _value: SetValue = {
      data: value,
      time: now
    };

    try {
      window.sessionStorage.setItem(key, JSON.stringify(_value));
      return value;
    } catch (e) {
      console.error(e);
      return null;
    }
  },

  /**
   * Removes the key/value pair with the given key,
   * if a key/value pair with the given key exists.
   * @param {key} string The key identifier of data to remove
   * @returns {boolean} {value} if the data was removed
   */
  remove(key: string): void {
    window.sessionStorage.removeItem(key);
  },

  /**
   * Removes all key/value pairs, if there are any.
   */
  clear(): void {
    window.sessionStorage.clear();
  }
};

if (typeof sessionStorage === "undefined" || sessionStorage === null) {
  storage = {
    get(key: string): string | string[] | Object | Object[] | null {
      console.warn("sessionStorage is not defined");
      return key;
    },
    set(key: string, value: any): any {
      console.warn("sessionStorage is not defined");
      return { key, value };
    },
    remove: (): void => {
      console.warn("sessionStorage is not defined");
    },
    clear: (): void => {
      console.warn("sessionStorage is not defined");
    }
  };
}

export default storage;
