import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { BackendService } from '../../../../services/backend/backend.service';
import { ToastrService } from 'ngx-toastr';
import * as moment from 'moment';

@Component({
	selector: 'app-datetime',
	templateUrl: './datetime.component.html',
	styleUrls: ['./datetime.component.css']
})
export class DatetimeComponent implements OnInit {
	isProcessing:boolean = true;
	isDisabled:boolean = true;
	timeLeft:number = 0;
	buttonText:string = "Mise à jour";
	interval:any;
	time:string = "";
	date:string = "";

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

	ngOnInit(): void {
		this.isProcessing = false;
	}

	timeChanged(time:string): void {
		console.log("Nouvelle heure: ", time);
		this.time = time;
		if(this.time && this.date) {
			this.isDisabled = false;
		}
	}

	dateChanged(event:MatDatepickerInputEvent<Date>): void {
		var date = moment(event.value);
		this.date = date.format("YYYY-MM-DD").toString();
		if(this.time && this.date) {
			this.isDisabled = 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 {
		this.setTimeoutDisabledButton(5);
		var newDateTime:string = this.date + " " + this.time + ":00";
		console.log("Nouvelle date et heure: ", newDateTime);
		this.bs.updateDatetime({'datetime':newDateTime}).subscribe(
			data => {
				this.toast.success("Mise à jour de la date et heure réussie");
			}, err => {
				if(err.status == 401) {
					this.router.navigateByUrl("/login");
				} else {
					this.toast.error(err.error.description);
				}
			}
		);

	}
}
