import {ChangeDetectorRef, Component, OnInit} from '@angular/core';
import {CalendarEvent, CalendarView} from 'angular-calendar';
import {Subject} from "rxjs";
import {ApiService} from "../../../../core/api/api.service";

@Component({
	selector: 'kt-calendario',
	templateUrl: './calendario.component.html',
	styleUrls: ['./calendario.component.scss']
})

export class CalendarioComponent implements OnInit {

	view: CalendarView = CalendarView.Week;
	CalendarView = CalendarView;
	viewDate: Date = new Date();
	events: CalendarEvent[] = [];
	refresh: Subject<any> = new Subject();
	clicked = true;
	titulo = "Agenda"
	isLoading = true;

	constructor(private api: ApiService, private ref: ChangeDetectorRef) {
	}

	ngOnInit() {
	}

	beforeViewRender(event): void {

		let startDay = new Date(event.period.start)
		let endDay = new Date(event.period.end)

		if(this.clicked){

			let data = {
				start_day: startDay.getFullYear() + '-' + (startDay.getMonth() + 1) + '-' + startDay.getDate(),
				end_day: (this.view == CalendarView.Week)? endDay.getFullYear() + '-' + (endDay.getMonth() + 1) + '-' + endDay.getDate() : null
			}
			this.isLoading = true;
			this.api.agenda.create(data).subscribe(res => {
				this.events = []
				res.forEach(agenda => {
					let evento = {
						start: new Date(agenda.start_day),
						end: new Date(agenda.end_day),
						title: "<b>"+ agenda.nombre_operador + "</b><br/>  " + agenda.hora_servicio + "<br/> " + agenda.duracion_servicio + "<br/> " + agenda.denominacion_cliente + "<br/> " + agenda.nombre_estatus,
						color: {
							primary: agenda.color_estatus,
							secondary: agenda.color_estatus
						}
					};
					this.events.push(evento)
				})
				this.refresh.next()
				this.isLoading = false
			}, () => {
				this.isLoading = false
			})
			this.clicked = false;
		}
	}

	btnChangeDate(){
		this.clicked = true
	}

	setView(view: CalendarView) {
		this.clicked = true;
		this.view = view;
	}
}
