import { Injectable } from "@angular/core";
import { LocalStorageService } from "ngx-localstorage";
import { LocalStorage, StorageMap } from '@ngx-pwa/local-storage';
import {  } from 'sha1';
let options = { hour12: false };

@Injectable({
  providedIn: "root"
})


export class DataService {

  db: any;

  constructor(
    private storage: LocalStorageService,
    private localStorage: LocalStorage,
    private storageMap: StorageMap
    ) { }

  async db_init() { }

  async set_item(_item: object) {
    try {
      let list: any;
      let has = await this.storageMap.has("instances").toPromise();
      if(!has) {
        list = await this.storageMap.set('instances', []).toPromise()
        return [];
      } else {
        list = await this.storageMap.get('instances').toPromise()
      }
      list.push({
        id: Date.now(),
        lines: _item,
        created_at: new Date(Date.now()).toLocaleString("en-US", options)
      });
      await this.storageMap.set('instances', list).toPromise();
      return true;
    } catch (e) {
      console.error(e);
    }
  }

  async get_all() {

    try {
      return await this.storageMap.get("instances").toPromise();
    } catch (e) {
      console.error(e);
    }
  }

  // get_singe_instance(line1, line2, line3) {

  // }

  async remove_item(_item: any) {
    try {
      let data: any;
      data = await this.storageMap.get("instances").toPromise();
      let tmp = data.findIndex((x:any)=> x['id'] === _item.id)
      data.splice(tmp, 1);
      return await this.storageMap.set('instances', data).toPromise();
    } catch (e) {
      console.error(e);
    }
  }
}
