import { Injectable } from '@angular/core';
import { Observable, of, Subscriber } from 'rxjs';
import { HitAWodService } from '../services/hit-a-wod.service';

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

    info:any;
    private dateResponse:string;
    company_id:number;
    box_id:number;
    data_ini:string;
    data_fi:string;

    constructor(private api:HitAWodService) {}

    getDashboardInfo(company_id:number, box_id?:number, data_ini?:string, data_fi?:string){
        if (!this.iGotResponse(company_id,box_id,data_ini,data_fi)) {
            return this.api.dashboard(company_id, box_id, data_ini, data_fi);
        } else {
            return new Observable<any>((subscriber: Subscriber<any>) => subscriber.next(this.info));
        }
        
    }

    deleteResponse() {
        this.company_id = null;
        this.box_id = null;
        this.data_ini = null;
        this.data_fi = null;
        this.info = null;
        this.dateResponse = null;
    }

    pushResponse(company_id:number, box_id:number, data_ini:string, data_fi:string, response:any) {
        if (!this.iGotResponse(company_id,box_id,data_ini,data_fi)) {
            this.company_id = company_id;
            this.box_id = box_id;
            this.data_ini = data_ini;
            this.data_fi = data_fi;
            this.info = response;
            this.dateResponse = (new Date()).toString();
        }
    }

    iGotResponse(company_id:number, box_id?:number, data_ini?:string, data_fi?:string) {
        if (
            this.company_id == company_id &&
            this.box_id == box_id &&
            this.data_ini == data_ini &&
            this.data_fi == data_fi &&
            this.responseIsRecent()
        ) return true;

        return false;
    }

    responseIsRecent() {
        const date = new Date(this.dateResponse);
        const currentDate = new Date();

        const diffMs = (currentDate.getTime() - date.getTime()); // milliseconds between now & Christmas
        const diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); // minutes

        return diffMins <= 10;
    }

}