import {Component, OnInit, Input} from '@angular/core';
import {FormGroup, FormArray, FormBuilder, Validators} from "@angular/forms";
import { HelpContentService } from "../../services/help-content.service";
import { Page } from "../../domain/page";

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

export class DivIdFormComponent implements OnInit{
    @Input('group')
    myForm: FormGroup;
    @Input('communityPid')
    communityPid: string;
    @Input('pageId')
    pageId: string;
    @Input('availablePages')
    availablePages : Page[] = [];
    @Input('formPages')
    formPages: Page[] = [];

    private gotPages: boolean = false;

    public errorMessage: string;

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

    ngOnInit(): void {

    }
/*
    public get form() {
        return this._fb.group({
            _id : '',
            name : ['', Validators.required],
            page : [this.pageId,Validators.required],
            community : this.communityPid,
        });
    }

    public reset() {
        this.myForm.patchValue({
            _id : '',
            name : '',
            page: '',
            community: this.communityPid
        });
    }
*/



public toggle() {
  this.myForm.value.isCollapsed = !this.myForm.value.isCollapsed;
/*
  if(!this.myForm.value.isCollapsed) {
    let includedPages: Set<String> = new Set<String>();
    for(let pageName of this.myForm.value.pages) {
      includedPages.add(pageName._id);
    }

    let allPages = this.availablePages;

    let self = this;
    allPages.forEach(function (status, page, map) {
      if(includedPages.has(page._id)) {
        self.allPages.set(page, true);
      } else {
        self.allEntities.set(page, false);
      }            community: this.communityPid

    });


    if(!this.gotPages && this.myForm.value.pages.length > 0) {
      this.gotPages = true;
      this.getPages();
    }
  }
*/
}
/*
public getPages() {
  let self = this;
  this._helpContentService.getPages().subscribe(
    pages => {
        for(let page of pages) {
          let index = self.myForm.value.pages.indexOf(page._id);
          if(index >= 0) {
            self.formPages[index] = page;
          }
        }
    },
    error => this.handleError('System error retrieving pages', error));
}
*/

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

public get form() {
    return this._fb.group({
        _id: '',
        name : ['', Validators.required],
        pages: this._fb.array([]),
        //pages: [[], Validators.required],
        community: this.communityPid,
        isCollapsed: [true]
    });
}

public reset() {
  console.info("reset");
    this.myForm.patchValue({
        _id : '',
        name : '',
        community: this.communityPid,
        isCollapsed: [true]
    });

    this.setPages([]);
    //this.initPages();
    this.formPages = [];
}

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

setPages(pages: string[]) {
  console.info(pages);
  //const pageFGs = pages.map(page => this._fb.group(page));
  //const pageFormArray = this._fb.array(pageFGs);
  const pageFormArray = this._fb.array(pages);
  //const pageFormArray = this.myForm.pages.patchValue([]);
  this.myForm.setControl('pages', pageFormArray);
}
/*
initPages() {
  let ctrl = <FormArray>this.form.controls.pages;
  ctrl.push(this._fb.group({
    page: ['', Validators.required]
  }))
}
*/
indexOfPageInForm(pageId: string): number {
  let index: number = -1;
  for(let i=0; i<this.formPages.length; i++) {
    if(this.formPages[i]._id == pageId) {
      index = i;
      break;
    }
  }
  return index;
}

public togglePage(status : boolean, page: Page) {
  let index: number = this.indexOfPageInForm(page._id);
  //index = this.formPages.indexOf(page);
  console.info("status: "+status + "   index: "+index);

  if(status && index<0) {
    this.formPages.push(page);
    //this.myForm.value.pages.push(page._id);
  } else if(!status){
    if(index >= 0) {
      this.formPages.splice(index, 1);
      //this.myForm.value.pages.splice(index, 1);
    }
  }
}

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