import { Component, ViewChild, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { FormGroup } from "@angular/forms";
import { DeleteConfirmationDialogComponent } from "../delete-confirmation-dialog.component";
import { HelpContentService } from "../../services/help-content.service";
import { DivHelpContent, CheckDivHelpContent, DivHelpContentFilterOptions } from "../../domain/div-help-content";
import { Page } from "../../domain/page";
import { Community } from "../../domain/community";
import { DivId } from "../../domain/divId";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

@Component({
    selector: 'div-help-contents',
    templateUrl: './div-help-contents.component.html',
})

export class DivHelpContentsComponent implements OnInit {

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

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

    public checkboxes : CheckDivHelpContent[] = [];

    public divHelpContents : DivHelpContent[] = [];

    public errorMessage: string;

    public formGroup : FormGroup;

    public pages: Page[];

    public checkboxAll : boolean = false;

    public filters : DivHelpContentFilterOptions = {id : '', active : null, text : new RegExp('')};

    public counter = {all : 0, active : 0, inactive : 0};

    public communities: Community[] = [];

    public selectedCommunityPid: string;

    public selectedPageId: string;

    public community: Community;

    public page: Page;
    public properties:EnvProperties = null;

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

           this.route.queryParams.subscribe(params => {

             this.selectedCommunityPid = params['community'];
             this.selectedPageId = params['page'];

             if(this.selectedCommunityPid && this.selectedPageId) {
               this.getDivHelpContents(this.selectedCommunityPid);
               this.getPage(this.selectedPageId);
               this.getCommunity(this.selectedCommunityPid);
             } else {
               this.selectedPageId = "";
               this.getCommunities();
             }
           });
        });
        // this.formGroup = this.formComponent.form;
    }

    constructor(private route: ActivatedRoute, private _helpService: HelpContentService, private router : Router) {}

    getPage(pageId: string) {
      let self = this;
      this._helpService.getPage(pageId, this.properties.adminToolsAPIURL).subscribe(
          page => {
              self.page = page;
            }
          );
    }

    getCommunity(communityPid: string) {
      let self = this;
      this._helpService.getCommunity(communityPid, this.properties.adminToolsAPIURL).subscribe(
          community => {
              self.community = community;
            }
          );
    }

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

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

    public countDivHelpContents() {
        this.counter = {all : 0, active : 0, inactive : 0};
        let filter = Object.assign({},this.filters);
        filter.active = null;
        this.divHelpContents.forEach(_ => {
            if(this.filterDivHelpContent(_,filter)){
                if (_.isActive==true) this.counter.active++;
                else this.counter.inactive++
            }
        });
        this.counter.all = this.counter.active + this.counter.inactive;
    }

    getDivHelpContents(community_pid: string) {
        let self = this;
        this._helpService.getCommunityDivHelpContents(community_pid, this.properties.adminToolsAPIURL).subscribe(
            divHelpContents => {
                self.divHelpContents = divHelpContents as Array<DivHelpContent>;
                self.counter.all = self.divHelpContents.length;
                self.checkboxes = [];
                /*self.pageHelpContents.forEach(_ => {
                  let page: Page = _.page as Page;
                  if(!self.selectedPageId || (page._id == self.selectedPageId)) {
                    self.checkboxes.push(<CheckPageHelpContent>{pageHelpContent : _, checked : false});
                  }
                });*/
                for (let i = self.divHelpContents.length - 1; i >= 0; i -= 1) {
                  let divId: DivId = self.divHelpContents[i].divId as DivId;
                  let pages: Page[] =  divId.pages as Page[];
                  const pageIds = pages.map(x => x._id);

                  if(!self.selectedPageId || pageIds.includes(self.selectedPageId)/*(page._id == self.selectedPageId)*/) {
                    self.checkboxes.push(<CheckDivHelpContent>{divHelpContent : self.divHelpContents[i], checked : false});
                  } else {
                    self.divHelpContents.splice(i, 1);
                  }
                }

                self.countDivHelpContents();
            },
            error => this.handleError('System error retrieving page contents', error));
    }

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

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

    public applyCheck(flag : boolean) {
        this.checkboxes.forEach(_ => _.checked = flag);
        this.checkboxAll = false;
    }

    public getSelectedDivHelpContents() : string[] {
        return this.checkboxes.filter(divHelpContent => divHelpContent.checked == true)
            .map(checkedDivHelpContent => checkedDivHelpContent.divHelpContent).map(res => res._id);
    }

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

    public confirmDeleteSelectedDivHelpContents() {
        this.deleteConfirmationModal.ids = this.getSelectedDivHelpContents();
        this.deleteConfirmationModal.showModal();
    }

    public confirmedDeleteDivHelpContents(ids : string[]) {
        this._helpService.deleteDivHelpContents(ids, this.properties.adminToolsAPIURL).subscribe(
            _ => this.deleteDivHelpContentsFromArray(ids),
            error => this.handleError('System error deleting the selected class content(s)', error)
        );
    }

    private deleteDivHelpContentsFromArray(ids : string[]) : void {
        for(let id of ids) {
            let iqc = this.checkboxes.findIndex(_ => _.divHelpContent._id == id);
            let iq = this.divHelpContents.findIndex(_ => _._id == id);
            this.checkboxes.splice(iqc, 1);
            this.divHelpContents.splice(iqc, 1);
        }
        this.countDivHelpContents();
    }

    public editDivHelpContent(id : string) {
        //this.router.navigate(['/pageContents/edit/', _id]);
        if(this.selectedPageId) {
          this.router.navigate( ['/classContents/edit/'], { queryParams: { "classContentId": id, "community": this.selectedCommunityPid, "pageId": this.selectedPageId  } } );
        } else {
          this.router.navigate( ['/classContents/edit/'], { queryParams: { "classContentId": id, "community": this.selectedCommunityPid } } );
        }
    }

    public toggleDivHelpContents(status : boolean, ids : string[]) {
        this._helpService.toggleDivHelpContents(ids,status, this.properties.adminToolsAPIURL).subscribe(
            () => {
                for(let id of ids) {
                    let i = this.checkboxes.findIndex(_ => _.divHelpContent._id == id);
                    this.checkboxes[i].divHelpContent.isActive=status;
                }
                this.countDivHelpContents();
                this.applyCheck(false);
            },
            error => this.handleError('System error changing the status of the selected page content(s)', error)
        );
    }

    public saveDivHelpContent(data : any):void {
        this._helpService.insertOrUpdateDivHelpContent(data, this.properties.adminToolsAPIURL).subscribe(
            divHelpContent => this.divHelpContentSavedSuccessfully(divHelpContent),
            error => this.handleError('System error saving the specified help content', error)
        );

    }

    public divHelpContentSavedSuccessfully(divHelpContent: DivHelpContent) {
        this.checkboxes.push(<CheckDivHelpContent>{divHelpContent : divHelpContent, checked : false});
        this.divHelpContents.push(divHelpContent);
        this.applyCheck(false);
        this.countDivHelpContents();
    }

    public divHelpContentUpdatedSuccessfully(divHelpContent : DivHelpContent) {
        this.checkboxes.find(checkItem => checkItem.divHelpContent._id==divHelpContent._id).divHelpContent = divHelpContent;
        let index = this.divHelpContents.findIndex(checkItem => checkItem._id==divHelpContent._id);
        this.divHelpContents[index] = divHelpContent;
        this.applyCheck(false);
        this.countDivHelpContents();
    }


    public filterDivHelpContent(divHelpContent : DivHelpContent, filters : DivHelpContentFilterOptions) : boolean {
        let divId: DivId = divHelpContent.divId as DivId;
        let pages: Page[] = <Page[]>divId.pages;
        let pageIds: string[] = pages.map(x => x._id);

        let idFlag = filters.id == '' || /*(<Page[]>divId.pages)._id == filters.id*/ pageIds.includes(filters.id);
        let activeFlag = filters.active == null || divHelpContent.isActive == filters.active;
        let textFlag = filters.text.toString() == '' || (divHelpContent.content).match(filters.text) != null;
        return idFlag && activeFlag && textFlag;
    }

    public applyFilter() {
        this.checkboxes = [];
        this.divHelpContents.filter(item => this.filterDivHelpContent(item,this.filters)).forEach(
            _ => this.checkboxes.push(<CheckDivHelpContent>{divHelpContent: _, checked: false})
        );
        this.countDivHelpContents();
    }

    public filterByPage(event: any) {
        this.filters.id = event.target.value;
        this.applyFilter();
    }

    public displayAllDivHelpContents() {
        this.filters.active = null;
        this.applyFilter();
    }

    public displayActiveDivHelpContents() {
        this.filters.active = true;
        this.applyFilter();
    }

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

    public displayInactiveDivHelpContents() {
        this.filters.active = false;
        this.applyFilter();
    }

    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.getDivHelpContents(community_pid);
    }
}
