import { Component, Input, OnInit } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { FieldEditorModel } from '@app/ui/admin/dataset-profile/admin/field-editor-model';
import { FieldSetEditorModel } from '@app/ui/admin/dataset-profile/admin/field-set-editor-model';
import { SectionEditorModel } from '@app/ui/admin/dataset-profile/admin/section-editor-model';
import { BaseComponent } from '@common/base/base.component';
import { Guid } from '@common/types/guid';
import { takeUntil } from 'rxjs/operators';

@Component({
	selector: 'app-dataset-profile-editor-section-component',
	templateUrl: './dataset-profile-editor-section.component.html',
	styleUrls: ['./dataset-profile-editor-section.component.scss']
})

export class DatasetProfileEditorSectionComponent extends BaseComponent implements OnInit {
	@Input() form: FormGroup;
	@Input() dataModel: SectionEditorModel;
	@Input() indexPath: string;
	@Input() viewOnly: boolean;

	constructor() { super(); }

	ngOnInit() {
		this.form.root.get('pages').valueChanges
			.pipe(takeUntil(this._destroyed))
			.subscribe(x =>
				this.keepPageSelectionValid(x)
			);
	}

	addField() {
		const fieldSet: FieldSetEditorModel = new FieldSetEditorModel();
		const field: FieldEditorModel = new FieldEditorModel();
		field.id = Guid.create().toString();
		fieldSet.fields.push(field);
		if (this.dataModel.fieldSets) {
			fieldSet.id = Guid.create().toString();
			this.dataModel.fieldSets.push(fieldSet);
		}
		(<FormArray>this.form.get('fieldSets')).push(fieldSet.buildForm());
	}

	addSectioninSection() {
		const section: SectionEditorModel = new SectionEditorModel();
		this.dataModel.sections.push(section);
		(<FormArray>this.form.get('sections')).push(section.buildForm());
	}

	DeleteSectionInSection(index) {
		this.dataModel.sections.splice(index, 1);
		(<FormArray>this.form.get('sections')).removeAt(index);
	}

	deleteFieldSet(index) {
		this.dataModel.fieldSets.splice(index, 1);
		(<FormArray>this.form.get('fieldSets')).removeAt(index);
	}

	keepPageSelectionValid(pagesJson: Array<any>) {
		const selectedPage = this.form.get('page').value as String;
		// const pages: Array<PageEditorModel> = JsonSerializer.fromJSONArray(pagesJson, Page);
		if (pagesJson.find(elem => elem.id === selectedPage) === undefined) {
			this.form.get('page').reset();
		}
	}

	getFieldTile(formGroup: FormGroup, index: number) {
		if (formGroup.get('title') && formGroup.get('title').value && formGroup.get('title').value.length > 0) { return formGroup.get('title').value; }
		return "Field " + (index + 1);
	}
}
