/**
 * Created by stefania on 7/13/17.
 */
import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
import { FormGroup } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
import { HelpContentService } from "../../services/help-content.service";
import { PageHelpContent, CheckPageHelpContent, PageHelpContentFilterOptions } from "../../domain/page-help-content";
import { Page } from "../../domain/page";
import { Community } from "../../domain/community";
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 {Title} from '@angular/platform-browser';

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

export class PageHelpContentsComponent implements OnInit {

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

    // @ViewChild('deleteConfirmationModal')
    // public deleteConfirmationModal : DeleteConfirmationDialogComponent;
    @ViewChild('AlertModalDeletePageHelpContents') alertModalDeletePageHelpContents;
    private selectedPageContents: string[] = [];

    public checkboxes : CheckPageHelpContent[] = [];

    public pageHelpContents : PageHelpContent[] = [];

    //public errorMessage: string;

    public formGroup : FormGroup;

    public pages: Page[];

    public checkboxAll : boolean = false;

    public filters : PageHelpContentFilterOptions = {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 | Page 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);
             }
           });
      });
        // this.formGroup = this.formComponent.form;
    }

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

    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(['/pageContents'], { queryParams: { "communityId": this.selectedCommunityPid} });
                } else {
                  this.page = page;
                  this.getPageHelpContents(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.getCommunityPages(community_pid, "", this.properties.adminToolsAPIURL).subscribe(
        this._helpService.getPages(this.properties.adminToolsAPIURL, community_pid, true).subscribe(
          pages => {
              this.pages = pages;
              this.getPageHelpContents(this.selectedCommunityPid);
            },
            error => this.handleError('System error retrieving pages', error));
      }
    }

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

    getPageHelpContents(community_pid: string) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this._helpService.getCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL).subscribe(
            pageHelpContents => {
                this.pageHelpContents = pageHelpContents as Array<PageHelpContent>;
                this.counter.all = this.pageHelpContents.length;
                this.checkboxes = [];

                for (let i = this.pageHelpContents.length - 1; i >= 0; i -= 1) {
                //for (let i = 0; i < this.pageHelpContents.length; i++) {
                  let page: Page =  this.pageHelpContents[i].page as Page;
                  if(!this.selectedPageId || (page._id == this.selectedPageId)) {
                    this.cutContent(this.pageHelpContents[i]);
                    this.checkboxes.unshift(<CheckPageHelpContent>{pageHelpContent : this.pageHelpContents[i], checked : false});
                  } else {
                    this.pageHelpContents.splice(i, 1);
                  }
                }

                this.countPageHelpContents();

                this.showLoading = false;
            },
            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 getSelectedPageHelpContents() : string[] {
        return this.checkboxes.filter(pageHelpContent => pageHelpContent.checked == true)
            .map(checkedPageHelpContent => checkedPageHelpContent.pageHelpContent).map(res => res._id);
    }

    public confirmDeletePageHelpContent(id : string) {
        //this.deleteConfirmationModal.ids = [id];
        //this.deleteConfirmationModal.showModal();
        this.selectedPageContents = [id];
        this.confirmModalOpen();
    }

    public confirmDeleteSelectedPageHelpContents() {
        //this.deleteConfirmationModal.ids = this.getSelectedPageHelpContents();
        //this.deleteConfirmationModal.showModal();
        this.selectedPageContents = this.getSelectedPageHelpContents();
        this.confirmModalOpen();
    }

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

    public confirmedDeletePageHelpContents(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.deletePageHelpContents(this.selectedPageContents, this.properties.adminToolsAPIURL).subscribe(
            _ => {
              this.deletePageHelpContentsFromArray(this.selectedPageContents);
              this.showLoading = false;
            },
            error => this.handleUpdateError('System error deleting the selected page content(s)', error)
        );
      }
    }

    private deletePageHelpContentsFromArray(ids : string[]) : void {
        for(let id of ids) {
            let iqc = this.checkboxes.findIndex(_ => _.pageHelpContent._id == id);
            let iq = this.pageHelpContents.findIndex(_ => _._id == id);
            this.checkboxes.splice(iqc, 1);
            this.pageHelpContents.splice(iqc, 1);
        }
        this.countPageHelpContents();
    }

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

    public togglePageHelpContents(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.togglePageHelpContents(ids,status, this.properties.adminToolsAPIURL).subscribe(
            () => {
                for(let id of ids) {
                    let i = this.checkboxes.findIndex(_ => _.pageHelpContent._id == id);
                    this.checkboxes[i].pageHelpContent.isActive=status;
                }
                this.countPageHelpContents();
                this.applyCheck(false);
            },
            error => this.handleUpdateError('System error changing the status of the selected page content(s)', error)
        );
      }
    }

    public pageHelpContentSavedSuccessfully(pageHelpContent: PageHelpContent) {
        this.cutContent(pageHelpContent);
        this.checkboxes.push(<CheckPageHelpContent>{pageHelpContent : pageHelpContent, checked : false});
        this.pageHelpContents.push(pageHelpContent);
        this.applyCheck(false);
        this.countPageHelpContents();
    }

    public pageHelpContentUpdatedSuccessfully(pageHelpContent : PageHelpContent) {
        this.checkboxes.find(checkItem => checkItem.pageHelpContent._id==pageHelpContent._id).pageHelpContent = pageHelpContent;
        let index = this.pageHelpContents.findIndex(checkItem => checkItem._id==pageHelpContent._id);
        this.pageHelpContents[index] = pageHelpContent;
        this.applyCheck(false);
        this.countPageHelpContents();
    }


    public filterPageHelpContent(pageHelpContent : PageHelpContent, filters : PageHelpContentFilterOptions) : boolean {
      let idFlag = filters.id == '' || (<Page>pageHelpContent.page)._id == filters.id;
      let activeFlag = filters.active == null || pageHelpContent.isActive == filters.active;
      let textFlag = filters.text.toString() == '' || (pageHelpContent.content).match(filters.text) != null
        || ((<Page>pageHelpContent.page).name).match(filters.text) != null;
      return idFlag && activeFlag && textFlag;
    }

    public cutContent(pageHelpContent: PageHelpContent) {
      pageHelpContent.content = pageHelpContent.content.replace(/<[^>]*>/g, '');
      pageHelpContent.content = pageHelpContent.content.replace(/(\r\n|\n|\r| +(?= ))|\s\s+/gm," ");

      if(pageHelpContent.content.length > 200) {
        pageHelpContent.content = pageHelpContent.content.substr(0, 200) + "...";
      }
    }

    public applyFilter() {
        this.checkboxes = [];
        this.pageHelpContents.filter(item => this.filterPageHelpContent(item,this.filters)).forEach(
            _ => {
              this.cutContent(_);
              this.checkboxes.push(<CheckPageHelpContent>{pageHelpContent: _, checked: false})
            }
        );
        this.countPageHelpContents();
    }

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

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

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

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

    public displayInactivePageHelpContents() {
        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 newPageContent() {
      if(this.selectedPageId) {
        this.router.navigate( ['/pageContents/new'], { queryParams: {communityId: this.selectedCommunityPid, pageId: this.selectedPageId} } );
      } else {
        this.router.navigate( ['/pageContents/new'], { queryParams: {communityId: this.selectedCommunityPid} } );
      }
    }
}
