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

@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;

    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 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.getPageHelpContents(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.getCommunities(this.properties.adminToolsAPIURL).subscribe(
            communities => {
                self.communities = communities;
                self.selectedCommunityPid = self.communities[0].pid;
                this.getPages(self.selectedCommunityPid);
                this.getPageHelpContents(self.selectedCommunityPid);
        },
        error => this.handleError('System error retrieving communities', error));
    }

    getPages(community_pid: string) {
        this._helpService.getCommunityPages(community_pid, this.properties.adminToolsAPIURL).subscribe(
            pages => this.pages = pages,
            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) {
        let self = this;
        this._helpService.getCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL).subscribe(
            pageHelpContents => {
                self.pageHelpContents = pageHelpContents as Array<PageHelpContent>;
                self.counter.all = self.pageHelpContents.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.pageHelpContents.length - 1; i >= 0; i -= 1) {
                  let page: Page =  self.pageHelpContents[i].page as Page;
                  if(!self.selectedPageId || (page._id == self.selectedPageId)) {
                    self.checkboxes.push(<CheckPageHelpContent>{pageHelpContent : self.pageHelpContents[i], checked : false});
                  } else {
                    self.pageHelpContents.splice(i, 1);
                  }
                }

                self.countPageHelpContents();
            },
            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();
    }

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

    public confirmedDeletePageHelpContents(ids : string[]) {
        this._helpService.deletePageHelpContents(ids, this.properties.adminToolsAPIURL).subscribe(
            _ => this.deletePageHelpContentsFromArray(ids),
            error => this.handleError('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, "community": this.selectedCommunityPid, "pageId": this.selectedPageId  } } );
        } else {
          this.router.navigate( ['/pageContents/edit/'], { queryParams: { "pageContentId": id, "community": this.selectedCommunityPid } } );
        }
    }

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

    public savePageHelpContent(data : any):void {
        console.log(data);
        this._helpService.savePageHelpContent(data, this.properties.adminToolsAPIURL).subscribe(
            pageHelpContent => this.pageHelpContentSavedSuccessfully(pageHelpContent),
            error => this.handleError('System error saving the specified help content', error)
        );
    }

    public pageHelpContentSavedSuccessfully(pageHelpContent: 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;
        return idFlag && activeFlag && textFlag;
    }

    public applyFilter() {
        this.checkboxes = [];
        this.pageHelpContents.filter(item => this.filterPageHelpContent(item,this.filters)).forEach(
            _ => 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) {
        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.getPageHelpContents(community_pid);
    }
}
