import { Inject, Injectable } from '@angular/core';
import { environment } from '@environment';
import { AppSettings } from '@shared/models-legacy';
import { APP_SETTINGS } from '@shared/services';

@Injectable()
export class FadeService {
    timer: ReturnType<typeof setTimeout>;
    timer2: ReturnType<typeof setTimeout>;

    constructor(
        @Inject(APP_SETTINGS) private settings: AppSettings,
    ) {
        this.timer = undefined;
        this.timer2 = undefined;
    }

    fadePage() {
        const body = document.getElementsByTagName("body")[0];
        const div = document.createElement("div");
        div.innerText = "Данные устарели, обновите страницу!";
        div.style.position = 'fixed';
        div.style.top = '0';
        div.style.left = '0';
        div.style.textAlign = 'center';
        div.style.paddingTop = '20%';
        div.style.width = '100%';
        div.style.height = '100%';
        div.style.backgroundColor = 'rgba(255, 255, 255, 0.7)';
        div.style.zIndex = '9999';
        body?.appendChild(div);
    }

    redirectPage() {
        window.location.assign('/'); 
    }

    start() {
        this.stop();
        this.timer = setTimeout(this.fadePage, environment.refreshPauseMin * 1000 * 60);
        this.timer2 = setTimeout(this.redirectPage, environment.refreshStopMin * 1000 * 60);
    }

    stop() {
        if (this.timer !== undefined) {
            clearTimeout(this.timer);
            this.timer = undefined;
        }
        if (this.timer2 !== undefined) {
            clearTimeout(this.timer2);
            this.timer2 = undefined;
        }
    }
}
