import * as _ from 'lodash';
import { IStorage } from './IStorage';

const IN_DOCUMENT_ID = '__stringifyr' as const

export function createDocumentStorage(_document: typeof document): IStorage {
  const node = (() => {
    const element = _document.getElementById(IN_DOCUMENT_ID);
    if (element) {
      return element;
    }

    const node = _document.createElement("span");
    node.id = IN_DOCUMENT_ID;
    node.style.display = 'none';
    node.style.visibility = 'hidden';
    _document.body.appendChild(node);
    return node;
  })();

  function root() {
      try {
        const data = node.innerText;
        return JSON.parse(data);
      } catch (e) {
        return {};
      }
  }

  return {
    clear() {
      _document.removeChild(node);
    },

    getItem(key: string): string | undefined | null {
      try {
        const parsed = root();
        return _.get(parsed, key, null);
      } catch (e) {
        return null;
      }
    },

    setItem(key: string, value: string): void {
      const parsed = root();
      _.set(parsed, key, value);
      node.innerText = JSON.stringify(parsed);
    }
  }
}
