/**
 * Created by stefania on 7/13/17.
 */
import {Component, OnInit, Input} from '@angular/core';
import { ActivatedRoute, Router } 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';

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';

@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;

    public showLoading: boolean = false;
    public errorMessage: string = '';

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

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

    public toggle() {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        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>) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.showLoading = true;
        this.errorMessage = "";

        this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
          entities => {
              for(let entity of entities) {
                if(includedEntities.has(entity._id)) {
                  this.allEntities.set(entity, true);
                } else {
                  this.allEntities.set(entity, false);
                }
              }
              this.showLoading = 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: '',
            openaire: true,
            connect: false,
            communities: true,
            top: true,
            bottom: true,
            left: true,
            right: true,
            type: ['', Validators.required],
            entities: this._fb.array([]),
            _id : '',
            isCollapsed: [true]
        });
    }

    public reset() {
        this.myForm.patchValue({
            route : '',
            name : '',
            type: '',
            isEnabled: '',
            openaire: true,
            connect: false,
            communities: true,
            top: true,
            bottom: true,
            left: true,
            right: true,
            _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);
    }

    public toggleEntity(status : boolean, id : string, entity: Entity) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        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;
          }
        }

        this.allEntities.set(entity, status);

        if(status && index<0) {
          this.myForm.value.entities.push(entity);
        } else  if(!status){
          if(index >= 0) {
            this.myForm.value.entities.splice(index, 1);
          }
        }
      }
    }

    handleError(message: string, error) {
        this.errorMessage = message;
        console.log('Server responded: ' + error);
        this.showLoading = false;
    }

}
