import { ChangeDetectionStrategy, ChangeDetectorRef, Component, Input, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { FormArray, FormGroup } from '@angular/forms';
import { BaseComponent } from '@common/base/base.component';
import { takeUntil } from 'rxjs/operators';
import { DatasetDescriptionCompositeFieldEditorModel } from '../../../dataset-description-form.model';
import { FormFocusService } from '../../../form-focus/form-focus.service';
import { LinkToScroll } from '../../../tableOfContentsMaterial/table-of-contents';
import { VisibilityRulesService } from '../../../visibility-rules/visibility-rules.service';

@Component({
	selector: 'app-form-section-inner',
	templateUrl: './form-section-inner.component.html',
	styleUrls: ['./form-section-inner.component.scss'],
	changeDetection: ChangeDetectionStrategy.OnPush
})
export class FormSectionInnerComponent extends BaseComponent implements OnInit, OnChanges {

	//@Input() section: DatasetDescriptionSectionEditorModel;
	@Input() datasetProfileId: String;
	// @Input() compositeFieldFormGroup: FormGroup;
	@Input() form: FormGroup;
	@Input() pathName: string;
	@Input() path: string;
	// @Input() i: number;
	@Input() linkToScroll: LinkToScroll;
	//trackByFn = (index, item) => item ? item['id'] : null;
	panelExpanded = true;
	// sub = true;
	subsectionLinkToScroll: LinkToScroll;

	constructor(
		public visibilityRulesService: VisibilityRulesService,
		private changeDetector: ChangeDetectorRef,
		private formFocusService: FormFocusService
	) {
		super();
		this.visibilityRulesService.getElementVisibilityMapObservable().pipe(takeUntil(this._destroyed)).subscribe(x => {
			this.changeDetector.markForCheck();
		});
	}

	ngOnInit() {
		// if (this.section) {
		// 	this.form = this.visibilityRulesService.getFormGroup(this.section.id);
		// }
	}

	ngOnChanges(changes: SimpleChanges) {

		// if (changes['linkToScroll']) {
		// 	if (changes['linkToScroll'].currentValue && changes['linkToScroll'].currentValue.section) {

		// 		if (this.pathName === changes['linkToScroll'].currentValue.section) {
		// 			this.panelExpanded = true;
		// 		} else if (changes['linkToScroll'].currentValue.section.includes(this.pathName)) {
		// 			this.subsectionLinkToScroll = changes['linkToScroll'].currentValue;
		// 			this.panelExpanded = true;
		// 		}
		// 	}
		// }
	}

	// ngAfterViewInit() {
	// 	this.visibilityRulesService.triggerVisibilityEvaluation();
	// }

	addMultipleField(fieldsetIndex: number) {
		const compositeFieldToBeCloned = (this.form.get('compositeFields').get('' + fieldsetIndex) as FormGroup).getRawValue();
		const multiplicityItemsArray = (<FormArray>(this.form.get('compositeFields').get('' + fieldsetIndex).get('multiplicityItems')));
		const compositeField: DatasetDescriptionCompositeFieldEditorModel = new DatasetDescriptionCompositeFieldEditorModel().cloneForMultiplicity(compositeFieldToBeCloned, multiplicityItemsArray.length);
		multiplicityItemsArray.push(compositeField.buildForm());
	}

	deleteCompositeFieldFormGroup(compositeFildIndex: number) {
		const numberOfItems = this.form.get('compositeFields').get('' + compositeFildIndex).get('multiplicityItems').get('' + 0).get('fields').value.length;
		for (let i = 0; i < numberOfItems; i++) {
			const multiplicityItem = this.form.get('compositeFields').get('' + compositeFildIndex).get('multiplicityItems').get('' + 0).get('fields').get('' + i).value;
			this.form.get('compositeFields').get('' + compositeFildIndex).get('fields').get('' + i).patchValue(multiplicityItem);
		}
		(<FormArray>(this.form.get('compositeFields').get('' + compositeFildIndex).get('multiplicityItems'))).removeAt(0);
	}

	deleteMultipeFieldFromCompositeFormGroup(compositeFildIndex: number, fildIndex: number) {
		const multiplicityItemsArray = (<FormArray>(this.form.get('compositeFields').get('' + compositeFildIndex).get('multiplicityItems')))
		multiplicityItemsArray.removeAt(fildIndex);
		multiplicityItemsArray.controls.forEach((control, i) => {
			try {
				control.get('ordinal').setValue(i);
			} catch {
				throw 'Could not find ordinal';
			}
		});
	}

	// isElementVisible(fieldSet: CompositeField): boolean {
	// 	return fieldSet && fieldSet.fields && fieldSet.fields.length > 0
	// }

	// next(compositeField: CompositeField) {
	// 	this.formFocusService.focusNext(compositeField);
	// }
}
