import { Injectable } from '@angular/core';
import { localstoreService } from './localstore.service'
import { SHA1 }  from  'crypto-js'
import { ExpedienteTask } from '../models/dailyworktask.model';

@Injectable({
  providedIn: 'root'
})
export class ExpedientegdStoreService {

  // main data
  private _list: ExpedienteTask[] = []
  // local storage keyName
  private keyName: string; 
  private _count = 0

  constructor() {

    this.keyName = (SHA1(this.constructor.name)).toString()
    
    setTimeout(()=> { 
      let restore = localstoreService.get(this.keyName, {})
      this._list = restore.list || []
      this._count = parseInt(restore.count) || 0
    }, 10)

  }

  get list() {
    return this._list
  }
  get count() {
    return this._count  || 0
  }
  set count(value: number) {
    this._count = value
    this.save()
  }

  reset(eventsList: any) {
    this._list = eventsList

    this.count = this._list.length
    this.save()
  }

  private save() {
    setTimeout(()=>{ 
      localstoreService.set(this.keyName,{
        list: this._list,
        count: this._count
      })
    }, 10)
    
  }

}

export const ExpedienteGdStore = new ExpedientegdStoreService()