import { Injectable } from '@angular/core';
import { Event } from '../models/event.model';
import { localstoreService } from './localstore.service'
import { AES, enc, SHA1 }  from  'crypto-js'
import { EventList } from '../models/agenda/AgendaEventList';

@Injectable({
  providedIn: 'root'
})

export class ToDayEventStorageService {

  // main data
  private _eventsList:EventList[] = []
  // local storage keyName
  private keyName: string; 
  private _count = 0

  constructor() {

    this.keyName = (SHA1(this.constructor.name+ 'home/eventSource')).toString()
    
    
    setTimeout(() => {
      let restore = localstoreService.get(this.keyName, {})
      this._eventsList = restore.eventsList || []
      this._count =  parseInt(restore.count) || 0
    }, 10)

  }

  get eventsList() {
    return this._eventsList || []
  }
  get count() {
    return this._count
  }
  set count(value: number) {
    this._count = value
    this.save()
  }

  reset(eventsList: EventList[]) {
    this._eventsList = eventsList

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

  private save() {
    setTimeout(()=>{ 
      localstoreService.set(this.keyName,{
        eventsList :this._eventsList,
        count: this._eventsList
      })
    }, 10)
    
  }

}

export const ToDayEventStorage = new ToDayEventStorageService()