import { AfterViewInit, Component, Input, OnChanges, OnInit, SimpleChanges, ViewChild } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { MatHorizontalStepper } from '@angular/material/stepper';
import { Rule } from '@app/core/model/dataset-profile-definition/rule';
import { LinkToScroll } from '@app/ui/misc/dataset-description-form/tableOfContentsMaterial/table-of-contents';
import { VisibilityRulesService } from '@app/ui/misc/dataset-description-form/visibility-rules/visibility-rules.service';
import { BaseComponent } from '@common/base/base.component';

@Component({
	selector: 'app-dataset-description-form',
	templateUrl: './dataset-description-form.component.html',
	styleUrls: ['./dataset-description-form.component.scss']
})
export class DatasetDescriptionFormComponent extends BaseComponent implements OnInit, AfterViewInit, OnChanges {

	@ViewChild('stepper') stepper: MatHorizontalStepper;
	@Input() path: string;
	@Input() form: FormGroup;
	@Input() visibilityRules: Rule[] = [];
	@Input() datasetProfileId: String;
	@Input() linkToScroll: LinkToScroll;

	constructor(
		private visibilityRulesService: VisibilityRulesService,
	) {
		super();
	}

	ngOnInit() {
		this.visibilityRulesService.buildVisibilityRules(this.visibilityRules, this.form);
	}

	ngOnChanges(changes: SimpleChanges) {

		// When the form is changed set stepper index to 0.
		if (this.stepper && changes['form'] && !changes['form'].isFirstChange()) {
			this.stepper.selectedIndex = 0;
		} else if (this.stepper && changes['linkToScroll'] && changes['linkToScroll'].currentValue) {
			if (changes['linkToScroll'].currentValue.page >= 0) {
				this.stepper.selectedIndex = changes['linkToScroll'].currentValue.page;
			}
		}
	}

	ngAfterViewInit() {

	}
}
