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 { DivIdFormComponent } from "./divId-form.component";
import { CheckDivId, DivId } from "../../domain/divId";
import { Community } from "../../domain/community";
import { Page } from "../../domain/page";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

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

export class DivIdsComponent implements OnInit {

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

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

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

    @ViewChild(DivIdFormComponent)
    public formComponent : DivIdFormComponent;

    public checkboxes : CheckDivId[] = [];

    public divIds : DivId[] = [];

    public errorMessage: string;

    public formGroup : FormGroup;

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

    public selectedCommunityPid: string;
    public communities: Community[] = [];
    public pages: Page[] = [];
    public properties:EnvProperties = null;
    public formPages: Page[] = [];

    ngOnInit() {
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
           this.formGroup = this.formComponent.form;
           this.route.queryParams.subscribe(params => {
             // if(params['community']) {
             //   this.getCommunity(params['community']);
             // } else {
             this.getCommunities();
             //}
           });
      });
    }

    constructor(private route: ActivatedRoute, private _helpContentService: HelpContentService) {}
/*
    getCommunity(community_pid: string) {
        let self = this;
        this._helpContentService.getCommunityFull(community_pid).subscribe(
            community => {
                self.communities = [community];
                this.checkboxes.push(<CheckCommunity>{community : community, checked : false});
        },
        error => this.handleError('System error retrieving communities', error));
    }
*/
    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.getDivIds(self.selectedCommunityPid);
                self.formGroup.patchValue({
                  community: self.selectedCommunityPid
                });
        },
        error => this.handleError('System error retrieving communities', error));
    }

    getPages(community_pid: string) {
        this._helpContentService.getCommunityPages(community_pid, this.properties.adminToolsAPIURL).subscribe(
            pages => this.pages = pages,
            error => this.handleError('System error retrieving pages', error));
    }

    getDivIds(community_pid: string) {
        let self = this;
        this._helpContentService.getDivIdsFull(community_pid, null, this.properties.adminToolsAPIURL).subscribe(
            divIds => {
                self.divIds = divIds;

                self.checkboxes = [];
                divIds.forEach(_ => {
                    self.checkboxes.push(<CheckDivId>{divId : _, checked : false});
                });
        },
        error => this.handleError('System error retrieving classes', 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 getSelectedDivIds() : string[] {
        return this.checkboxes.filter(divId => divId.checked == true).map(checkedDivId => checkedDivId.divId).map(res => res._id);
    }

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

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

    public confirmDeleteSelectedDivIds() {
        this.deleteConfirmationModal.ids = this.getSelectedDivIds();
        this.deleteConfirmationModal.showModal();
    }

    public confirmedDeleteDivIds(ids : string[]) {
        this._helpContentService.deleteDivIds(ids, this.properties.adminToolsAPIURL).subscribe(
           _ => this.deleteDivIdsFromArray(ids),
           error => this.handleError('System error deleting the selected classes', error)
        );
    }

    public editDivId(i : number) {
        let divId : DivId = this.checkboxes[i].divId;
        this.formPages = <Page[]>divId.pages;

        let pageIds: string[] = [];
        let index = 0;
        for(let page of <Page[]>divId.pages) {
          pageIds[index] = page._id;
          index++;
        }
        //divId.pages = pageIds;

        let community: Community = <Community>divId.community;
        this.formGroup.patchValue(divId);
        this.formGroup.patchValue({
          community: community._id
        });
        this.formComponent.setPages(pageIds);

        this.updateModal.showModal();
    }

    public divIdSavedSuccessfully(divId: DivId) {
        this.checkboxes.push(<CheckDivId>{divId : divId, checked : false});
        console.info("checkboxes length: "+this.checkboxes.length);
        this.applyCheck(false);
    }

    public divIdUpdatedSuccessfully(divId : DivId) {
        this.checkboxes.find(checkItem => checkItem.divId._id==divId._id).divId = divId;
        this.applyCheck(false);
    }

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

    public applyFilter() {
        this.checkboxes = [];
        this.divIds.filter(item => this.filterDivIds(item)).forEach(
            _ => this.checkboxes.push(<CheckDivId>{divId: _, checked: false})
        );
    }

    public filterDivIds(divId : DivId) : boolean {
        let textFlag = this.searchText.toString() == '' || (/*community.route + ' ' +*/divId.name).match(this.searchText) != null;
        return textFlag;
    }

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

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

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