import {Component, OnInit, Input} from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import {FormGroup, FormArray, FormBuilder, Validators} from "@angular/forms";
import { HelpContentService } from "../../services/help-content.service";
import { Page } from "../../domain/page";
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: 'divId-form',
    templateUrl: './divId-form.component.html',
})

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

    //public allPages : Page[] = [];
    public allPages: Map<Page, boolean> = new Map<Page, boolean>();
    private gotPages: boolean = false;

    public properties:EnvProperties = null;

    public showLoading: boolean = false;
    public errorMessage: string = '';
    selectedCommunityPid = null;
    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;
           this.route.queryParams.subscribe(params => {
             this.selectedCommunityPid = params['communityId'];
           });
         });
    }

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

    getPages(includedPages: 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.getPages(this.properties.adminToolsAPIURL,this.selectedCommunityPid).subscribe(
          pages => {
            //this.allPages = allPages;
            for(let page of pages) {
              if(includedPages.has(page._id)) {
                this.allPages.set(page, true);
              } else {
                this.allPages.set(page, false);
              }
            }
            this.showLoading = false;
          },
          error => this.handleError('System error retrieving pages', error)
        );
      }
    }

    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 includedPages: Set<String> = new Set<String>();
          for(let pageName of this.myForm.value.pages) {
            includedPages.add(pageName._id);
          }

          let allPages = this.allPages;

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


          if(!this.gotPages) {
            this.gotPages = true;
            this.getPages(includedPages);
          }
        }
      }
/////
    }

    public get form() {
        return this._fb.group({
            _id: '',
            name : ['', Validators.required],
            pages: this._fb.array([]),
            openaire: true,
            connect: false,
            communities: true,
            isCollapsed: [true]
        });
    }

    public reset() {
        this.myForm.patchValue({
            _id : '',
            name : '',
            openaire: true,
            connect: false,
            communities: true,
            isCollapsed: [true]
        });

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

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

    setPages(pages: Page[]) {
      //const pageFormArray = this._fb.array(pages);
      //this.myForm.setControl('pages', pageFormArray);

      const pageFGs = pages.map(page => this._fb.group(page));
      const pageFormArray = this._fb.array(pageFGs);
      this.myForm.setControl('pages', pageFormArray);
    }

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

      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);
        }
      }*/

      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('pages').value.length; i++) {
          if(this.myForm.get('pages').value[i]._id == page._id) {
            index = i;
            break;
          }
        }

        this.allPages.set(page, status);

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

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

        this.showLoading = false;
    }
}
