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

@Injectable({
  providedIn: 'root'
})

export class CalendarService {

  private _eventSource : EventListStore[]  = []
  private keyName: string; 

  localstoreService = localstoreService
  
  constructor() {
    
    this.keyName = (SHA1(this.constructor.name+ 'eventSource')).toString()

    let restore = this.localstoreService.get(this.keyName, [])

    setTimeout(()=>{
      restore.forEach((element:EventListStore, eventIndex) => {
        this._eventSource.push({
          startTime: new Date(element.startTime),
          endTime: new Date(element.endTime),
          allDay: element.allDay,
          event: element.event,
          calendarName: element.calendarName,
          profile: element.profile,
          id: element.id,
        });
  
      });
    },10)

  }

  ResetList(eventSource: EventListStore[]) {
    this._eventSource = eventSource

    setTimeout(() => {
      this.localstoreService.set(this.keyName, this._eventSource)
    }, 10)

  }

  get eventSource() {
    return this._eventSource || []
  }

  

  removeRange(rangeStartDate, rangeEndDate, profile) {
    this._eventSource = this._eventSource.filter((e)=> {
      if(new Date(rangeStartDate).getTime() <= new Date(e.startTime).getTime() &&
         new Date(rangeEndDate).getTime() >= new Date(e.endTime).getTime() && e.profile == profile) { 
        return false
      }
      return true
    })
  }

  pushEvent(eventsList: EventList[], profile: 'pr' | 'md') {

    let news = []
    eventsList.forEach((element, eventIndex) => {
      news.push({
        startTime: new Date(element.StartDate),
        endTime: new Date(element.EndDate),
        allDay: false,
        event: element,
        calendarName: element.CalendarName,
        profile: profile,
        id: element.EventId,
      });

    });

    let instance = this._eventSource.concat(news)

    const ids = instance.map(o => o.id)
    const filtered = instance.filter(({id}, index) => !ids.includes(id, index + 1))

    this._eventSource = (filtered)

    

    setTimeout(() => {

      this.localstoreService.set(this.keyName, this._eventSource)
      
    }, 10)
  }


  delete() {
    this._eventSource = []
  }
}


export const CalendarStore = new CalendarService()