/**
 * This file is part of Anis Client.
 *
 * @copyright Laboratoire d'Astrophysique de Marseille / CNRS
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

import { Component, Input, Output, EventEmitter, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

import { Instance, FileInfo } from 'src/app/metamodel/models';

@Component({
    selector: 'app-instance-form',
    templateUrl: 'instance-form.component.html'
})
export class InstanceFormComponent implements OnInit {
    @Input() instance: Instance;
    @Input() rootDirectory: FileInfo[];
    @Input() rootDirectoryIsLoading: boolean;
    @Input() rootDirectoryIsLoaded: boolean;
    @Output() loadRootDirectory: EventEmitter<string> = new EventEmitter();
    @Output() onSubmit: EventEmitter<Instance> = new EventEmitter();

    public designFormGroup = new FormGroup({
        design_color: new FormControl('#7AC29A', [Validators.required])
    });

    public searchFormGroup = new FormGroup({
        search_by_criteria_allowed: new FormControl(true),
        search_multiple_allowed: new FormControl(false),
        search_multiple_all_datasets_selected: new FormControl({value: false, disabled: true})
    });

    public documentationFormGroup = new FormGroup({
        documentation_allowed: new FormControl(false)
    });

    public form = new FormGroup({
        name: new FormControl('', [Validators.required]),
        label: new FormControl('', [Validators.required]),
        data_path: new FormControl(''),
        config: new FormGroup({
            design: this.designFormGroup,
            search: this.searchFormGroup,
            documentation: this.documentationFormGroup
        })
    });

    ngOnInit() {
        if (this.instance) {
            this.form.patchValue(this.instance);
            if (this.searchFormGroup.controls.search_multiple_allowed.value) {
                this.searchFormGroup.controls.search_multiple_all_datasets_selected.enable();
            }
        }
    }

    onChangeDataPath(path: string) {
        this.loadRootDirectory.emit(path);
        this.form.markAsDirty();
    }

    submit() {
        if (this.instance) {
            this.onSubmit.emit({
                ...this.instance,
                ...this.form.value
            });
        } else {
            this.onSubmit.emit(this.form.value);
        }
    }
}