import { Component, OnInit } from '@angular/core';
import { first } from 'rxjs/operators';

import { User } from '@/_models';
import { UserService, AuthenticationService, FireFormsService} from '@/_services';
import {FireForm} from "@/_models/fire-form";
import {Router} from "@angular/router";
import data from '../../../configuration.json';

@Component({ templateUrl: 'home.component.html' })
export class HomeComponent implements OnInit {
    currentUser: User;
    showNewForms: boolean;
    users = [];
    fireForms = [];
    hotWorkPermits = [];
    newForms = [];
    toBeReinstated = [];
    title: string;
    show: string;
    data;

    constructor(
        private authenticationService: AuthenticationService,
        private userService: UserService,
        private router: Router,
        private fireServices: FireFormsService,
    ) {
        this.currentUser = this.authenticationService.currentUserValue;
        this.title = 'FIRE, SECURITY AND FIRE PROTECTION SHUTDOWN NOTIFICATION';
        this.show = '1';
        // setInterval(() => {
        //     this.show = this.show + 1;
        // }, 5000);
        this.data = data;
    }

    ngOnInit() {
        this.loadAllUsers();
        this.loadAllFireForms();
        this.loadAllToBeReinstated();
        this.loadAllHotWorkPermits();
        this.loadAllNewForms();
    }

    deleteUser(id: number) {
        this.userService.delete(id)
            .pipe(first())
            .subscribe(() => this.loadAllUsers());
    }

    loadForm(fireForm: FireForm) {
        this.router.navigate(['/form'], { queryParams: fireForm });
    }

    approve(fireForm: FireForm, value: boolean) {
        fireForm.status = value ? "APPROVED" : "DISAPPROVED";
        this.fireServices.register(fireForm)
            .pipe(first())
            .subscribe(() => this.loadAllFireForms());
    }

    reinstatedForm(fireForm: FireForm) {
        fireForm.status = "REINSTATED";
        this.fireServices.register(fireForm)
            .pipe(first())
            .subscribe(() => this.loadAllFireForms());
    }

    private loadAllUsers() {
        this.userService.getAll()
            .pipe(first())
            .subscribe(users => this.users = users);
    }

    private loadAllFireForms() {
        this.fireServices.getAll()
            .pipe(first())
            .subscribe(fireForms => this.fireForms = fireForms);
    }

    private loadAllHotWorkPermits() {
        this.fireServices.getAllHotWorkPermits()
            .pipe(first())
            .subscribe(hotWorkPermits => this.hotWorkPermits = hotWorkPermits);
    }

    private loadAllNewForms() {
        this.fireServices.getAllNewForms()
            .pipe(first())
            .subscribe(newHotWorkPermits => this.newForms = newHotWorkPermits);
    }

    private loadAllToBeReinstated() {
        this.fireServices.getAllToBeReinstated()
            .pipe(first())
            .subscribe(toBeReinstated => this.toBeReinstated = toBeReinstated);
    }
}