import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {first} from 'rxjs/operators';
import {AlertService, AuthenticationService, FireFormsService} from '@/_services';
import {User} from '@/_models';
import {FireForm} from "@/_models/fire-form";
import data from '../../../configuration.json';
import {HttpClient} from "@angular/common/http";


@Component({templateUrl: 'form.component.html'})
export class FormComponent implements OnInit {
    registerForm: FormGroup;
    currentForm: FireForm;
    loading = false;
    allowSubmit: boolean;
    submitted = false;
    currentUser: User;
    Hospitals: String[];
    Buildings: String[][];
    Floors: String[][][];
    dataMap;
    fileName = '';

    constructor(
        private formBuilder: FormBuilder,
        private router: Router,
        private route: ActivatedRoute,
        private authenticationService: AuthenticationService,
        private fireFormService: FireFormsService,
        private http: HttpClient,
        private alertService: AlertService
    ) {
        this.authenticationService.currentUser.subscribe(x => this.currentUser = x);
        // @ts-ignore
        this.currentForm = this.route.snapshot.queryParams || null;
        this.dataMap = data.Configuration.HospitalList;
        this.Hospitals = new Array;
        this.Buildings = new Array;
        this.Floors = new Array;
        for (let hospital in data.Configuration.HospitalList) {
            this.Hospitals.push(hospital);
            this.Buildings[hospital] = new Array();
            this.Floors[hospital] = new Array();
            for (let building in data.Configuration.HospitalList[hospital].BuildingList) {
                this.Buildings[hospital].push(building);
                this.Floors[hospital][building] = new Array();
                this.Floors[hospital][building].push(data.Configuration.HospitalList[hospital].BuildingList[building])
            }
        }
    }

    ngOnInit() {
        if (Object.keys(this.currentForm).length !== 0) {
            this.allowSubmit = false;
            this.registerForm = this.formBuilder.group({
                employeeId: this.currentUser.id,
                employeeName: this.currentUser.first_name + ' ' + this.currentUser.last_name,
                hospitalName: [this.currentForm.hospitalName, Validators.required],
                siteName: [this.currentForm.siteName, Validators.required],
                level: [this.currentForm.level, Validators.required],
                fireSystem: [this.currentForm.fireSystem, Validators.required],
                affectedArea: [this.currentForm.affectedArea, Validators.required],
                shutdownDate: [new Date(this.currentForm.shutdownDate).toISOString().slice(0, 16), Validators.required],
                reinstated: this.currentForm.reinstated,
                reinstatedDate: this.currentForm.reinstatedDate == null ? this.currentForm.reinstatedDate : new Date(this.currentForm.reinstatedDate).toISOString().slice(0, 16),
                pdf: this.fileName,
                emergency: this.currentForm.emergency,
                continuousShutdown: this.currentForm.continuousShutdown,
                reason: this.currentForm.reason,
                hotWorkPermit: this.currentForm.hotWorkPermit,
                comment: this.currentForm.comment,
                mainsWater: this.currentForm.mainsWater,
                chilledWater: this.currentForm.chilledWater,
                domesticWater: this.currentForm.domesticWater,
                highTempHotWaterSteam: this.currentForm.highTempHotWaterSteam,
                domesticHotWater: this.currentForm.domesticHotWater,
                lVPower: this.currentForm.lVPower,
                hVPower11kv: this.currentForm.hVPower11kv,
                sewer: this.currentForm.sewer,
                fuelLines: this.currentForm.fuelLines,
                medicalGasesVacuum: this.currentForm.medicalGasesVacuum,
                fireProtection: this.currentForm.fireProtection,
                bmsAlarms: this.currentForm.bmsAlarms,
                airCondition: this.currentForm.airCondition,
                compressedGases: this.currentForm.compressedGases,
                telecomsICT: this.currentForm.telecomsICT,
                others: this.currentForm.others,
                othersTxt: this.currentForm.othersTxt,
                additionalInfo: this.currentForm.additionalInfo,
                safetyImplications: this.currentForm.safetyImplications,
                lockOffRequired: this.currentForm.lockOffRequired,
                safetySignsPosted: this.currentForm.safetySignsPosted,
                safetyPrecautions: this.currentForm.safetyPrecautions,
                airMonitoringRequired: this.currentForm.airMonitoringRequired,
                associatedHazards: this.currentForm.associatedHazards,
                hotWorkPermitRequired: this.currentForm.hotWorkPermitRequired,
                fumesDustNoise: this.currentForm.fumesDustNoise,
                hvPermitRequired: this.currentForm.hvPermitRequired,
                location: this.currentForm.location,
                status: this.currentForm.status,
            });
        } else {
            this.allowSubmit = true;
            this.registerForm = this.formBuilder.group({
                employeeId: this.currentUser.id,
                employeeName: this.currentUser.first_name + ' ' + this.currentUser.last_name,
                hospitalName: ['', Validators.required],
                siteName: ['', Validators.required],
                level: ['', Validators.required],
                fireSystem: ['', Validators.required],
                affectedArea: ['', Validators.required],
                shutdownDate: ['', Validators.required],
                reinstated: false,
                reinstatedDate: [''],
                pdf: [this.fileName],
                emergency: [''],
                continuousShutdown: false,
                reason: [''],
                hotWorkPermit: false,
                comment: [''],
                mainsWater: false,
                chilledWater: false,
                domesticWater: false,
                highTempHotWaterSteam: false,
                domesticHotWater: false,
                lVPower: false,
                hVPower11kv: false,
                sewer: false,
                fuelLines: false,
                medicalGasesVacuum: false,
                fireProtection: false,
                bmsAlarms: false,
                airCondition: false,
                compressedGases: false,
                telecomsICT: false,
                others: false,
                othersTxt: [''],
                additionalInfo: [''],
                safetyImplications: false,
                lockOffRequired: false,
                safetySignsPosted: false,
                safetyPrecautions: [''],
                airMonitoringRequired: false,
                associatedHazards: false,
                hotWorkPermitRequired: false,
                fumesDustNoise: false,
                hvPermitRequired: false,
                location: [''],
                status: ['NEW'],
            });
        }

        this.registerForm.get('hotWorkPermit').valueChanges.subscribe(value => {
                if (value) {
                    this.registerForm.get('additionalInfo').setValidators(Validators.required)
                    this.registerForm.get('location').setValidators(Validators.required)
                } else {
                    this.registerForm.get('additionalInfo').clearValidators();
                    this.registerForm.get('location').clearValidators();
                }
            }
        );
        this.registerForm.get('others').valueChanges.subscribe(value => {
                if (value) {
                    this.registerForm.get('othersTxt').setValidators(Validators.required)
                } else {
                    this.registerForm.get('othersTxt').clearValidators();
                }
            }
        );
        this.registerForm.get('reinstated').valueChanges.subscribe(value => {
                if (value) {
                    this.registerForm.get('reinstatedDate').setValidators(Validators.required)
                } else {
                    this.registerForm.get('reinstatedDate').clearValidators();
                }
            }
        );
        this.registerForm.get('continuousShutdown').valueChanges.subscribe(value => {
                if (value) {
                    this.registerForm.get('reason').setValidators(Validators.required)
                } else {
                    this.registerForm.get('reason').clearValidators();
                }
            }
        );
    }


    // convenience getter for easy access to form fields
    get f() {
        return this.registerForm.controls;
    }

    onSubmit() {
        this.submitted = true;

        // reset alerts on submit
        this.alertService.clear();

        // stop here if form is invalid
        if (this.registerForm.invalid) {
            return;
        }

        this.loading = true;
        this.fireFormService.register(this.registerForm.value)
            .pipe(first())
            .subscribe(
                data => {
                    this.alertService.success('Fire Form added successfully', true);
                    this.router.navigate(['/']);
                },
                error => {
                    this.alertService.error(error);
                    this.loading = false;
                });
    }

    createRange(num) {
        // return new Array(number);
        return Array.apply(null, {length: num}).map(Number.call, Number)
    }

    isAllowSubmit() {
        return this.allowSubmit;
    }

    s() {
        return "vff";
    }

    showBasedOnDate(date) {
        if (date == null) {
            this.registerForm.get('emergency').clearValidators();
            return false;
        }
        // here you can have as much logic as you would like, based on your needs.
        let twoDaysInMili = 48 * 60 * 60 * 1000;
        let retVal = new Date(date).getTime() - twoDaysInMili < new Date().getTime();
        if (retVal) {
            this.registerForm.get('emergency').setValidators(Validators.required)
        } else {
            this.registerForm.get('emergency').clearValidators();
        }
        return retVal;
    }

    onFileSelected(event) {
        const file: File = event.target.files[0];
        if (file) {
            this.fileName = file.name;
            const formData = new FormData();
            formData.append("file", file);
            const upload$ = this.http.post(`${config.apiUrl}/upload`, formData);
            upload$.subscribe();
        }
    }

}
