import {Component, OnInit} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HelperFunctions} from '../../../../openaireLibrary/utils/HelperFunctions.class';
import {SearchCommunityDataprovidersService} from '../../../../openaireLibrary/connect/contentProviders/searchDataproviders.service';
import {EnvProperties} from '../../../../openaireLibrary/utils/properties/env-properties';
import {ContentProvider} from '../../../../openaireLibrary/utils/entities/contentProvider';
import {FormArray, FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ManageCommunityContentProvidersService} from '../../../../services/manageContentProviders.service';
import {Title} from '@angular/platform-browser';

@Component({
  selector: 'criteria',
  templateUrl: './criteria.component.html'
})

export class CriteriaComponent implements OnInit {
  public community: string = '';
  public openaireId: string = '';
  public dataProvider: ContentProvider = null;
  public selectioncriteria: FormGroup;
  private properties: EnvProperties;
  showLoading = true;
  public errorMessage: string;

  constructor(private route: ActivatedRoute, private _router: Router,
              private title: Title,
              private searchCommunityDataprovidersService: SearchCommunityDataprovidersService,
              private manageCommunityContentProvidersService: ManageCommunityContentProvidersService,
              private fb: FormBuilder) {
  }

  ngOnInit() {
    this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
      this.properties = data.envSpecific;
      this.route.queryParams.subscribe(params => {
        if (params['communityId']) {
          this.community = params['communityId'];
        }
        if (params['openaireId']) {
          this.openaireId = params['openaireId'];
        }
        this.title.setTitle('Administration Dashboard | Criteria');
        this.searchCommunityDataprovidersService.searchDataproviders(this.properties, this.community).subscribe(dataProviders => {
          dataProviders.forEach(dataProvider => {
            if (dataProvider.openaireId == this.openaireId) {
              this.dataProvider = dataProvider;
            }
          });
          if (!this.dataProvider) {
            this._router.navigate(['manage-content-providers'],
              {queryParams: {'communityId': this.community}});
          }
          this.buildForm();
          this.showLoading = false;
        });
        HelperFunctions.scroll();
      });
    });
  }

  public ngOnDestroy() {
  }

  buildForm() {
    this.selectioncriteria = this.fb.group({
      criteria: this.fb.array([])
    });
    let selectionCriteria = this.dataProvider.selectioncriteria;
    if (selectionCriteria) {
      selectionCriteria.criteria.forEach(criterion => {
        let constraintArray: FormArray = this.fb.array([]);
        criterion.constraint.forEach(constraint => {
          constraintArray.push(this.fb.group({
            field: this.fb.control(constraint.field, Validators.required),
            verb: this.fb.control(constraint.verb, Validators.required),
            value: this.fb.control(constraint.value, Validators.required)
          }));
        });
        this.criteria.push(this.fb.group({
          constraint: constraintArray
        }));
      });
    }
  }

  public get criteria(): FormArray {
    return this.selectioncriteria.get('criteria') as FormArray;
  }

  public getConstraint(i: number): FormArray {
    return this.criteria.at(i).get('constraint') as FormArray;
  }

  public addCriteria() {
    let constraintArray: FormArray = this.fb.array([
      this.fb.group({
        field: this.fb.control('', Validators.required),
        verb: this.fb.control('contains', Validators.required),
        value: this.fb.control('', Validators.required)
      })
    ]);
    this.criteria.push(this.fb.group({
      constraint: constraintArray
    }));
  }

  public addConstraint(i: number) {
    let constraintArray: FormArray = this.criteria.at(i).get('constraint') as FormArray;
    constraintArray.push(this.fb.group({
      field: this.fb.control('', Validators.required),
      verb: this.fb.control('contains', Validators.required),
      value: this.fb.control('', Validators.required)
    }));
  }

  public removeConstraint(i: number, j: number) {
    let constraintArray: FormArray = this.criteria.at(i).get('constraint') as FormArray;
    constraintArray.removeAt(j);
    if (constraintArray.length === 0) {
      this.criteria.removeAt(i);
    }
  }

  save() {
    this.errorMessage = null;
    if (this.selectioncriteria.status === 'VALID') {
      this.dataProvider.selectioncriteria = this.selectioncriteria.value;
      this.manageCommunityContentProvidersService.
      saveContentProvider(this.properties, this.dataProvider).subscribe( () => {
        this._router.navigate(['manage-content-providers'], {
          queryParams: {communityId: this.dataProvider.communityId}
        });
      });
    } else {
      this.errorMessage = 'Please fill all fields of each constraint or remove all constraints with empty fields.';
    }
  }
}
