import { Component, OnInit, Input,
    ChangeDetectorRef, ChangeDetectionStrategy, ViewChild, Inject } from '@angular/core'
import { UntypedFormGroup, UntypedFormControl, Validators } from '@angular/forms'

import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog'

import { projectFields, ProjectField } from './fields'
import { Project } from '../../../openapi'

export interface DialogData {
    project: Project
}

@Component({
    selector: 'gisaf-admin-project-dialog',
    templateUrl: 'dialog.component.html',
    styleUrls: ['dialog.component.css'],
})
export class GisafAdminProjectDialogComponent implements OnInit {
    formGroup: UntypedFormGroup

    constructor(
        public dialogRef: MatDialogRef<GisafAdminProjectDialogComponent>,
        @Inject(MAT_DIALOG_DATA) public data: DialogData
    ) {}

    ngOnInit() {
        let project: Project = this.data['project']
        this.formGroup = new UntypedFormGroup({})
        //this.formGroup.addControl('id', new FormControl(project.id))
        for (let projectField of projectFields) {
            this.formGroup.addControl(
                projectField.name,
                new UntypedFormControl(
                    project[projectField.name] || projectField.defaultValue,
                    projectField.validators,
                )
            )
        }
    }

    save() {
        // Ugly hack for just getting an ISO date like YYYY-MM-DD
        projectFields.filter(
            f => f.type == 'date'
        ).forEach(
            f => {
                if (this.formGroup.value[f.name] instanceof Date) {
                    let qq = this.formGroup.value[f.name]
                    this.formGroup.value[f.name] = [
                        qq.getFullYear(),
                        qq.getMonth().toFixed().padStart(2, 0),
                        qq.getDate().toFixed().padStart(2, 0)
                    ].join('-')
                }
            }
        )
        this.dialogRef.close(this.formGroup.value);
    }
}
