import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { BackendService } from '../../../../services/backend/backend.service';
import { Scheduler, Horaire, Day } from '../../../../models/scheduler.model';
import { Parameters } from '../../../../models/parameters.model';
import { ToastrService } from 'ngx-toastr';
import { Observable, throwError } from 'rxjs';
import { catchError, map, startWith } from 'rxjs/operators';

@Component({
	selector: 'app-hours',
	templateUrl: './hours.component.html',
	styleUrls: ['./hours.component.css']
})
export class HoursComponent implements OnInit {
	schedule:Day[];
	isProcessing:boolean = true;
	isDisabled:boolean = true;
	schedCols:number = 0;
	schedRows:number = 0;
	colorFlag:string = 'red';
	defaultOp:string = 'Manuel ON';
	operations:string[] = ['Manuel ON', 'Manuel OFF', 'Horaires'];
	timeLeft:number = 0;
	buttonText:string = "Mise à jour";
	interval:any;

	constructor( private bs:BackendService,
				 private router:Router,
				 private toast:ToastrService ) { }

	ngOnInit(): void {
		this.bs.retreiveScheduler().subscribe(
			(datas:Scheduler) => {
				this.schedule = datas.days;
				this.defaultOp = datas.mode;
				this.schedCols = Object.keys(datas.days).length;
				this.schedRows = Object.keys(datas.days[0].horaires).length;
				this.isProcessing = false;
				this.isDisabled = false;
			}, err => {
				if(err.status == 401) {
					this.router.navigateByUrl("/login");
				} else {
					this.toast.error(err.error.description);
				}
				this.isProcessing = false;
			}
		);
	}

	setTimeoutDisabledButton(timeout:number): void {
		this.timeLeft = timeout;
		this.isDisabled = true;
		this.buttonText = "Mise à jour" + " ... (" + this.timeLeft + ")";
		this.interval = setInterval(() => {
			if(this.timeLeft > 0) {
				this.timeLeft--;
				this.buttonText = "Mise à jour" + " ... (" + this.timeLeft + ")";
			} else {
				this.isDisabled = false;
				this.buttonText = "mise à jour";
				clearInterval(this.interval);
			}
		},1000)
	}

	onUpdate(): void {
		let sched:Scheduler = {
			mode:this.defaultOp,
			days:this.schedule
		};
		if(this.defaultOp == "Manuel ON") {
			this.setTimeoutDisabledButton(90);
		} else {
			this.setTimeoutDisabledButton(20);
		}
		this.bs.updateScheduler(sched).subscribe(
			data => {
				this.toast.success("Mise à jour des horaires réussie");
			}, err => {
				if(err.status == 401) {
					this.router.navigateByUrl("/login");
				} else {
					this.toast.error(err.error.description);
				}
			}
		);
	}

	updateCell(col: number, row: number): void {
		if(this.schedule[col].horaires[row].state == 1) {
			this.schedule[col].horaires[row].state = 0;
		} else {
			this.schedule[col].horaires[row].state = 1;
		}
	}
}
