import { Injectable } from '@angular/core';
import { CustomCalendarEvent, EventListStore } from 'src/app/models/agenda/AgendaEventList';
import { DateService } from '../date.service';

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

	constructor(
    	private dateService: DateService
	){}

	
	filterProfile(eventSource: EventListStore[] = [], profile: 'md' | 'pr' |  'all') {
		return eventSource.filter((e) => e.profile == profile)
	}

	getEventInsideRange(eventSource: EventListStore[], rangeStartDate, randEndDate) {
		return eventSource.filter((e)=> {
			if(new Date(rangeStartDate).getTime() <= new Date(e.startTime).getTime() &&
					new Date(randEndDate).getTime() >= new Date(e.endTime).getTime()) { 
				return true
			}
			return false
		})
	}

	filterSegment(eventSource: EventListStore[], segment): EventListStore[] {
		return eventSource.filter( data => data.calendarName == segment)
	}

	daysBetween(){ }

	list(eventSource: EventListStore[], profile: 'md' | 'pr' | 'all', rangeStartDate, randEndDate, {segment = 'Combinado', selectedDate= null}) {

		// console.log('eventSource', eventSource ,'rangeStartDate', new Date(rangeStartDate).toLocaleDateString('pt') , 'randEndDate', new Date(randEndDate).toLocaleDateString('pt'))

		// // filter range
		// if(selectedDate) {
		// 	eventSource = eventSource.filter(data => 
		// 		data.startTime.toLocaleDateString('pt') >= new Date(rangeStartDate).toLocaleDateString('pt') && 
		// 		data.startTime.toLocaleDateString('pt') <= new Date(rangeStartDate).toLocaleDateString('pt')
		// 	)
		// }


		if(segment!='Combinado') {
			eventSource = this.filterSegment(eventSource, segment) 
		}
    
		if(profile != 'all') {
			eventSource = this.filterProfile(eventSource, profile)
		}

    	let newStracture:CustomCalendarEvent[];

		if(profile == 'md') {
			newStracture = this.encapsulation(eventSource, 'mdgpr');
		} else {
			newStracture = this.encapsulation(eventSource, 'pr');
		}

		return this.display(newStracture, profile, selectedDate)
	}

	display(list: CustomCalendarEvent[], profile, selectedDate) {
		let days = {};

		list.forEach( (event:CustomCalendarEvent, index)=> {

			var startDate: any = new Date(event.start);

			var endDate: any = this.dateService.EventEndDateTreatment({
				startTime: startDate, 
				endTime: event.end
			})
			
			const day = this.dateService.getDay(event.start) 
			
			event['manyDays'] = false
			event['todayOnly'] = this.dateService.isSameDate(event.start, event.end)

			if(!days.hasOwnProperty(day)) {
				days[day] = []
			}

			if (this.dateService.notSameDate(startDate, endDate)) {

        const diffDays = this.dateService.deferenceBetweenDays(endDate, startDate)

				if (diffDays <= 150 && !event.event.IsAllDayEvent ) {

					if (diffDays >= 1) {
						
						const StartEvent =  this.transForm(event, {startMany: true,endMany: false,	middle: false, profile})
						
						if(this.push(event, selectedDate)) days[day].push(StartEvent)
						
						let i = 1;
						
						// create event between date
						while (startDate.getFullYear() !=  endDate.getFullYear() || 
							startDate.getMonth() != endDate.getMonth() ||
							startDate.getDate() != endDate.getDate()) {

							const newDate = startDate.setDate(startDate.getDate()+ i)
							let otherDays =   this.dateService.getDay(newDate) 
								
							event['other'] = true
							
							event.start = newDate
							if(!days.hasOwnProperty(otherDays)) {

								days[otherDays] = []
							}
							
							if (!(startDate.getFullYear() !=  endDate.getFullYear() || 
							startDate.getMonth() != endDate.getMonth() ||
							startDate.getDate() != endDate.getDate())) {
								// last push

								const EndEvent = this.transForm(event, {startMany: false,endMany: true,	middle: false, profile})
								if(this.push(event, selectedDate)) days[otherDays].push(EndEvent)

							} else {

                const EndEvent = this.transForm(event, {startMany: false,endMany: true,	middle: true, profile})
                if(this.push(event, selectedDate)) days[otherDays].push(EndEvent)
							}
							
						}

					} else {


						if(this.push(event, selectedDate)) days[day].push(event)
					}
				} else {

					if(this.push(event, selectedDate)) days[day].push(event)
				}
			}

      if(this.push(event, selectedDate)) days[day].push(event)

		})

    // remove days that haven't event
    Object.entries(days).forEach(([index, value]) => {
      const _value: any = value

      if(_value.length == 0) {
        delete days[index]
      }

    })

		return days
	}


	push(event: any, selectedDate: Date) {

		return  new Date(event.start).getMonth() == selectedDate.getMonth() &&
				new Date(event.start).getFullYear() == selectedDate.getFullYear() && 
				new Date(event.start).getDate() >= selectedDate.getDate()
	}

	encapsulation(eventsList:EventListStore[], profile): CustomCalendarEvent[] {

		// remove all event
		let events: CustomCalendarEvent[] = [];

		eventsList.forEach((element, eventIndex) => {
			
			events.push({
				start: new Date(element.startTime),
				end: new Date(element.endTime),
				id: element.id,
				event: element.event,
			});

		});

		return events;
	}


  transForm(event:  CustomCalendarEvent, {startMany, endMany, middle, profile}) {
    return Object.assign({}, {
      start: event.start,
      end: event.end,
      id: event.id,
      profile: profile,
      event: {
        Subject: event.event.Subject,
        StartDate:  event.event.StartDate,
        EndDate: event.event.EndDate,
        Location:  event.event.Location,
        EventId:  event.event.EventId,
        CalendarName: event.event.CalendarName
      },
      Subject: event.event.Subject,
      startMany: false,
      endMany: true,
      middle: true
    })
  }


}
