interface LocalStorageItem {
   data: any;
   expirationTimestamp: number;
}

export class LocalStorage {
   public static get = (key: string, useExpired: boolean = false): any | null => {
      const storageItem = localStorage.getItem(key);
      if (!storageItem) {
         return null;
      }

      const item: LocalStorageItem = JSON.parse(storageItem) as LocalStorageItem;
      // check if item expired
      if (!useExpired && item.expirationTimestamp < LocalStorage.getCurrentTimestamp()) {
         item.data = null;
      }

      return item.data;
   };

   public static set = (key: string, value: any, ttlInMinutes = 5) => {

      if(ttlInMinutes <= 0) {
         return;
      }

      localStorage.setItem(key, JSON.stringify({
         data: value,
         expirationTimestamp: LocalStorage.getCurrentTimestamp() + (ttlInMinutes * 60000)
      } as LocalStorageItem));
   };

   public static remove = (key: string) => {
      localStorage.removeItem(key);
   };


   public static getItemTTL = (key: string) => {
      const storageItem = localStorage.getItem(key);
      if (!storageItem) {
         return null;
      }

      const item: LocalStorageItem = JSON.parse(storageItem) as LocalStorageItem;

      return (item.expirationTimestamp - this.getCurrentTimestamp()) / 60000;
   };

   private static getCurrentTimestamp(): number {
      if (!Date.now) {
         Date.now = function() {
            return new Date().getTime();
         };
      }

      return Date.now();
   }
}
