import { Injectable } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Pair } from '../../../../../common/types/pair';
import { CompositeField } from '../../../../core/model/dataset-profile-definition/composite-field';
import { VisibilityRulesService } from '../visibility-rules/visibility-rules.service';
import { groupBy } from 'lodash';

@Injectable()
export class FormFocusService {

	private compositeFields: Pair<CompositeField[], number>[] = [];

	constructor(
		private router: Router,
		private route: ActivatedRoute,
		private visibilityService: VisibilityRulesService
	) {

	}

	setFields(compositeFields: Pair<CompositeField[], number>[]) {
		this.compositeFields = compositeFields;
	}

	focusNext(field: CompositeField) {
		const flattenedCompositeFields = groupBy(this.compositeFields, x => x.right)
			.map(x => x.reduce((first: Pair<CompositeField[], number>, second: Pair<CompositeField[], number>) =>
				(new Pair<CompositeField[], number>(first.left.concat(second.left), first.right))));
		const page = flattenedCompositeFields.filter(x => x['left'].map(y => y.id).indexOf(field.id) !== -1)[0];
		let pageIndex = page['right'];
		const currentFields = page['left'].filter(x => this.visibilityService.checkElementVisibility(x.id)).map(x => x.id);
		const fieldIndex = currentFields.indexOf(field.id);
		if (fieldIndex === currentFields.length - 1) { pageIndex = pageIndex + 1; }
		this.router.navigate(['datasets/' + this.route.snapshot.url[0] + '/' + this.route.snapshot.url[1]], { fragment: page['left'].filter(x => this.visibilityService.checkElementVisibility(x.id))[fieldIndex].id, queryParams: { page: pageIndex } });
	}
}
