import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
import { Router, ActivatedRoute } from "@angular/router";
import { FormGroup } from "@angular/forms";
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';
import {SafeHtmlPipe} from '../../openaireLibrary/utils/pipes/safeHTML.pipe';

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
import {PageHelpContent} from "../../domain/page-help-content";
import {Title} from '@angular/platform-browser';

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

export class DivHelpContentsComponent implements OnInit {
    // @ViewChild('deleteConfirmationModal')
    // public deleteConfirmationModal : DeleteConfirmationDialogComponent;
    @ViewChild('AlertModalDeleteDivHelpContents') alertModalDeleteDivHelpContents;
    private selectedDivContents: string[] = [];

    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 keyword: string = "";

    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;

    public showLoading: boolean = true;
    public errorMessage: string = '';
    public updateErrorMessage: string = '';

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

           this.route.queryParams.subscribe(params => {
             HelperFunctions.scroll();
             this.title.setTitle('Administration Dashboard | Class Help Texts');
             this.selectedCommunityPid = params['communityId'];
             this.selectedPageId = params['pageId'];

             if(this.selectedCommunityPid && this.selectedPageId) {
               this.getPage(this.selectedPageId);
             } else if(this.selectedCommunityPid){
               this.selectedPageId = "";
               this.getPages(this.selectedCommunityPid);
             }
           });
        });
    }

    constructor(private element: ElementRef, private route: ActivatedRoute,
                private title: Title,
                private _helpService: HelpContentService, private router : Router) {}

    getPage(pageId: string) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this.showLoading = true;
        this.updateErrorMessage = "";
        this.errorMessage = "";
        this._helpService.getPage(pageId, this.properties.adminToolsAPIURL).subscribe(
            page => {
              if( (this.selectedCommunityPid == 'openaire' && !page.openaire)
                || (this.selectedCommunityPid == 'connect' && !page.connect)
                || (this.selectedCommunityPid != 'openaire' && this.selectedCommunityPid != 'connect' && !page.communities)) {
                this.router.navigate(['/classContents'], { queryParams: { "communityId": this.selectedCommunityPid} });
              } else {
                this.page = page;
                this.getDivHelpContents(this.selectedCommunityPid);
              }
            },
            error => this.handleError('System error retrieving page', error));
      }
    }

    getPages(community_pid: string) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this.showLoading = true;
        this.updateErrorMessage = "";
        this.errorMessage = "";

        this._helpService.getCommunityPagesWithDivId(community_pid, this.properties.adminToolsAPIURL).subscribe(
        //this._helpService.getPagesWithDivIds(community_pid, this.properties.adminToolsAPIURL).subscribe(
            pages => {
              this.pages = pages;
              this.getDivHelpContents(this.selectedCommunityPid);
            },
            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) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this._helpService.getCommunityDivHelpContents(community_pid, this.properties.adminToolsAPIURL).subscribe(
            divHelpContents => {
                this.divHelpContents = divHelpContents as Array<DivHelpContent>;
                this.counter.all = this.divHelpContents.length;
                this.checkboxes = [];

                for (let i = this.divHelpContents.length - 1; i >= 0; i -= 1) {
                //for (let i = 0; i < this.divHelpContents.length; i++) {
                  let divId: DivId = this.divHelpContents[i].divId as DivId;
                  let pages: Page[] =  divId.pages as Page[];
                  const pageIds = pages.map(x => x._id);

                  if(!this.selectedPageId || pageIds.includes(this.selectedPageId)) {
                    this.cutContent(this.divHelpContents[i]);
                    this.checkboxes.unshift(<CheckDivHelpContent>{divHelpContent : this.divHelpContents[i], checked : false});
                  } else {
                    this.divHelpContents.splice(i, 1);
                  }
                }

                this.countDivHelpContents();

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

    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();
        this.selectedDivContents = [id];
        this.confirmModalOpen();
    }

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

    private confirmModalOpen() {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this.alertModalDeleteDivHelpContents.cancelButton = true;
        this.alertModalDeleteDivHelpContents.okButton = true;
        this.alertModalDeleteDivHelpContents.alertTitle = "Delete Confirmation";
        this.alertModalDeleteDivHelpContents.message = "Are you sure you want to delete the help text(s)?";
        this.alertModalDeleteDivHelpContents.okButtonText = "Yes";
        this.alertModalDeleteDivHelpContents.open();
      }
    }

    public confirmedDeleteDivHelpContents(data: any) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this.showLoading = true;
        this.updateErrorMessage = "";

        this._helpService.deleteDivHelpContents(this.selectedDivContents, this.properties.adminToolsAPIURL).subscribe(
            _ => {
              this.deleteDivHelpContentsFromArray(this.selectedDivContents);
              this.showLoading = false;
            },
            error => this.handleUpdateError('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, "communityId": this.selectedCommunityPid, "pageId": this.selectedPageId  } } );
        } else {
          this.router.navigate( ['/classContents/edit/'], { queryParams: { "classContentId": id, "communityId": this.selectedCommunityPid } } );
        }
    }

    public toggleDivHelpContents(status : boolean, ids : string[]) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this.updateErrorMessage = "";

        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.handleUpdateError('System error changing the status of the selected page content(s)', error)
        );
      }
    }

    public divHelpContentSavedSuccessfully(divHelpContent: DivHelpContent) {
        this.cutContent(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
          || ((<DivId>divHelpContent.divId).name).match(filters.text) != null;
        return idFlag && activeFlag && textFlag;
    }

    public cutContent(divHelpContent: DivHelpContent) {
      divHelpContent.content = divHelpContent.content.replace(/<[^>]*>/g, '');
      divHelpContent.content = divHelpContent.content.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm," ");
      if(divHelpContent.content.length > 200) {
        divHelpContent.content = divHelpContent.content.substr(0, 200) + "...";
      }
    }

    public applyFilter() {
        this.checkboxes = [];
        this.divHelpContents.filter(item => this.filterDivHelpContent(item,this.filters)).forEach(
            _ => {
              this.cutContent(_);
              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) {
        this.errorMessage = message;
        console.log('Server responded: ' + error);

        this.showLoading = false;
    }

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

        this.showLoading = false;
    }

    public newClassContent() {
      if(this.selectedPageId) {
        this.router.navigate( ['/classContents/new'], { queryParams: {communityId: this.selectedCommunityPid, pageId: this.selectedPageId} } );
      } else {
        this.router.navigate( ['/classContents/new'], { queryParams: {communityId: this.selectedCommunityPid} } );
      }
    }
}
