/**
 * Created by stefania on 7/13/17.
 */
import {Component, OnInit, Input} from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import {FormGroup, FormArray, FormBuilder, Validators} from "@angular/forms";
import {Entity} from '../../domain/entity';
import { HelpContentService } from "../../services/help-content.service";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

@Component({
    selector: 'page-form',
    templateUrl: './page-form.component.html',
})

export class PageFormComponent implements OnInit{

    @Input('group')
    myForm: FormGroup;
    @Input('type')
    public type: string;

    public errorMessage: string;

    public allEntities: Map<Entity, boolean> = new Map<Entity, boolean>();
    private gotEntities: boolean = false;
    public properties:EnvProperties = null;

    constructor(private route: ActivatedRoute,public _fb: FormBuilder, private _helpContentService: HelpContentService){}

    ngOnInit(): void {
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
      });
    }

    public toggle() {
      this.myForm.value.isCollapsed = !this.myForm.value.isCollapsed;

      if(!this.myForm.value.isCollapsed) {
        let includedEntities: Set<String> = new Set<String>();
        for(let entityName of this.myForm.value.entities) {
          includedEntities.add(entityName._id);
        }

        let allEntities = this.allEntities;

        let self = this;
        allEntities.forEach(function (status, entity, map) {
          if(includedEntities.has(entity._id)) {
            self.allEntities.set(entity, true);
          } else {
            self.allEntities.set(entity, false);
          }
        });


        if(!this.gotEntities) {
          this.gotEntities = true;
          this.getEntities(includedEntities);
        }
      }
    }

    public getEntities(includedEntities: Set<String>) {
      let self = this;
      this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
        entities => {
            for(let entity of entities) {
              if(includedEntities.has(entity._id)) {
                self.allEntities.set(entity, true);
              } else {
                self.allEntities.set(entity, false);
              }
            }
      },
      error => this.handleError('System error retrieving community entities', error));
    }

    public getKeys( map) {
      return Array.from(map.keys());
    }

    public get form() {
        return this._fb.group({
            route : ['', Validators.required],
            name : ['', Validators.required],
            isEnabled: '',
            type: ['', Validators.required],
            entities: this._fb.array([]),
            _id : '',
            isCollapsed: [true]
        });
    }

    public reset() {
        this.myForm.patchValue({
            route : '',
            name : '',
            type: '',
            isEnabled: '',
            //entities: this._fb.array([]),
            _id : '',
            isCollapsed: [true]
        });

        this.setEntities([]);
    }

    public get entities(): FormArray {
      return this.myForm.get('entities') as FormArray;
    };

    setEntities(entities: Entity[]) {
      const entityFGs = entities.map(entity => this._fb.group(entity));
      const entityFormArray = this._fb.array(entityFGs);
      this.myForm.setControl('entities', entityFormArray);
    }

    addEntity() {
      this.myForm.value.entities.push(this._fb.group(new Entity()));
    }

    public toggleEntity(status : boolean, id : string, entity: Entity) {
      let index: number = -1;
      for(let i=0; i<this.myForm.get('entities').value.length; i++) {
        if(this.myForm.get('entities').value[i]._id == entity._id) {
          index = i;
          break;
        }
      }
      console.info("status: "+status + "   index: "+index);

      this.allEntities.set(entity, status);

      if(status && index<0) {
        this.myForm.value.entities.push(entity);
        console.info("push :   "+this.myForm.value.entities.length);
      } else  if(!status){
        if(index >= 0) {
          this.myForm.value.entities.splice(index, 1);
          console.info("delete :   "+this.myForm.value.entities.length);
        }
      }
/*
      this._helpContentService.toggleEntityOfPage(this.myForm.value._id,id,status).subscribe(
          () => {

          },
          error => this.handleError('System error changing the status of the enity of page', error)
      );
*/
    }

    handleError(message: string, error) {
        if(error == null) {
            this.reset();
        }
        this.errorMessage = message + ' (Server responded: ' + error + ')';
    }
}
