/**
 * Created by stefania on 7/13/17.
 */
import { Component, ViewChild, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { HelpContentService } from "../../services/help-content.service";
import { FormGroup } from "@angular/forms";
import { ModalFormComponent } from "../modal-form.component";
import { DeleteConfirmationDialogComponent } from "../delete-confirmation-dialog.component";
import { PageFormComponent } from "./page-form.component";
import { CheckPage, Page } from "../../domain/page";
import { Community } from "../../domain/community";
import { Entity } from "../../domain/entity";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

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

export class PagesComponent implements OnInit {

    // @ViewChild(ModalFormComponent)
    @ViewChild('saveModal')
    public modal:ModalFormComponent;

    @ViewChild('updateModal')
    public updateModal:ModalFormComponent;

    @ViewChild('deleteConfirmationModal')
    public deleteConfirmationModal : DeleteConfirmationDialogComponent;

    @ViewChild(PageFormComponent)
    public formComponent : PageFormComponent;

    public checkboxes : CheckPage[] = [];

    public pages : Page[] = [];
    public pageWithDivIds: string[] = [];

    public errorMessage: string;

    public formGroup : FormGroup;

    private searchText : RegExp = new RegExp('');

    public communities: Community[] = [];

    public selectedCommunityPid: string;

    public pagesType: string;
    public properties:EnvProperties = null;

    ngOnInit() {
        this.formGroup = this.formComponent.form;
        this.route.data
          .subscribe((data: { envSpecific: EnvProperties }) => {
             this.properties = data.envSpecific;
             //        this.getCommunities();

             this.route.queryParams.subscribe(params => {
               this.pagesType = "";
               if(params['type']) {
                 this.pagesType = params['type'];
               }
               this.getCommunities();
             });
        });
    }

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

    getPages(community_pid: string) {
        let self = this;

        if(this.pagesType) {
          this._helpContentService.getCommunityPagesByType(community_pid, "?page_type="+this.pagesType, this.properties.adminToolsAPIURL).subscribe(
              pages => {
                self.pagesReturned(pages);
              },
              error => this.handleError('System error retrieving pages', error));
        } else {
          this._helpContentService.getCommunityPages(community_pid, this.properties.adminToolsAPIURL).subscribe(
              pages => {
                self.pagesReturned(pages);
              },
              error => this.handleError('System error retrieving pages', error));
        }
    }

    getPagesWithDivIds(community_pid: string) {
      let self = this;
      this._helpContentService.getPagesWithDivIds(community_pid, this.properties.adminToolsAPIURL).subscribe(
          pages => {
            self.pageWithDivIds = pages[community_pid];
          },
          error => this.handleError('System error retrieving pages', error));
    }

    pagesReturned(pages: Page[]) {
      this.pages = pages;
      this.checkboxes = [];

      pages.forEach(_ => {
          this.checkboxes.push(<CheckPage>{page : _, checked : false});
      });
    }

    getCommunities() {
        let self = this;
        this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
            communities => {
                self.communities = communities;
                self.selectedCommunityPid = self.communities[0].pid;
                self.getPages(self.selectedCommunityPid);
                self.getPagesWithDivIds(self.selectedCommunityPid);
        },
        error => this.handleError('System error retrieving communities', error));
    }

    public showModal():void {
        this.modal.showModal();
    }

    public toggleCheckBoxes(event) {
        this.checkboxes.forEach(_ => _.checked = event.target.checked);
    }

    public applyCheck(flag : boolean) {
      console.info("applyCheck "+flag);
        this.checkboxes.forEach(_ => _.checked = flag);
    }

    public getSelectedPages() : string[] {
        return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
    }

    private deletePagesFromArray(ids : string[]) : void {
        for(let id of ids) {
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
            this.checkboxes.splice(i, 1);
        }
    }

    public confirmDeletePage(id : string) {
        this.deleteConfirmationModal.ids = [id];
        this.deleteConfirmationModal.showModal();
    }

    public confirmDeleteSelectedPages() {
        this.deleteConfirmationModal.ids = this.getSelectedPages();
        this.deleteConfirmationModal.showModal();
    }

    public confirmedDeletePages(ids : string[]) {
        this._helpContentService.deletePages(ids, this.properties.adminToolsAPIURL).subscribe(
            _ => this.deletePagesFromArray(ids),
            error => this.handleError('System error deleting the selected pages', error)
        );
    }

    public editPage(i : number) {
        let page : Page = this.checkboxes[i].page;
        this.formGroup.patchValue(page);
        const entityFGs = (page.entities as Entity[]).map(entity => this.formComponent._fb.group(entity));
        const entityFormArray = this.formComponent._fb.array(entityFGs);
        this.formGroup.setControl('entities', entityFormArray);
        console.info(this.formGroup.value);
        this.updateModal.showModal();
    }

    public pageSavedSuccessfully(page: Page) {
        this.checkboxes.push(<CheckPage>{page : page, checked : false});
        console.info("checkboxes length: "+this.checkboxes.length);
        this.applyCheck(false);
    }

    public pageUpdatedSuccessfully(page : Page) {
      console.info(page._id);
      console.info(this.checkboxes.find(checkItem => (checkItem.page._id == page._id)));
      console.info(page.entities);
        this.checkboxes.find(checkItem => checkItem.page._id==page._id).page = page;
        this.applyCheck(false);
    }

    public filterBySearch(text : string) {
        this.searchText = new RegExp(text,'i');
        this.applyFilter();
    }

    public applyFilter() {
        this.checkboxes = [];
        this.pages.filter(item => this.filterPages(item)).forEach(
            _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
        );
    }

    public filterPages(page : Page) : boolean {
        let textFlag = this.searchText.toString() == '' || (page.route + ' ' +page.name).match(this.searchText) != null;
        return textFlag;
    }

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



    public filterByCommunity(event: any) {
        this.selectedCommunityPid = event.target.value;
        this.applyCommunityFilter(this.selectedCommunityPid);
    }

    public applyCommunityFilter(community_pid: string) {
        this.getPages(community_pid);
        this.getPagesWithDivIds(community_pid);
    }

    public togglePages(status : boolean, ids : string[]) {
        this._helpContentService.togglePages(this.selectedCommunityPid,ids,status, this.properties.adminToolsAPIURL).subscribe(
            () => {
                for(let id of ids) {
                //     let i = this.checkboxes.findIndex(_ => _.page._id == id);
                //     this.checkboxes[i].page.isEnabled=status;
                // }
                  let i = this.checkboxes.findIndex(_ => _.page._id == id);
                  this.checkboxes[i].page.isEnabled=status;
                }
                this.applyCheck(false);
            },
            error => this.handleError('System error changing the status of the selected page(s)', error)
        );
    }


}
