/**
 * Created by stefania on 7/13/17.
 */
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 { CommunityFormComponent } from "./community-form.component";
import { CheckCommunity, Community } from "../../domain/community";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

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

export class CommunitiesComponent implements OnInit {

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

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

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

    @ViewChild(CommunityFormComponent)
    public formComponent : CommunityFormComponent;

    public checkboxes : CheckCommunity[] = [];

    public communities : Community[] = [];

    public errorMessage: string;

    public formGroup : FormGroup;

    private searchText : RegExp = new RegExp('');
    public properties:EnvProperties = null;
    ngOnInit() {
        this.formGroup = this.formComponent.form;

        this.route.data
          .subscribe((data: { envSpecific: EnvProperties }) => {
             this.properties = data.envSpecific;
             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, this.properties.adminToolsAPIURL).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.getCommunitiesFull(this.properties.adminToolsAPIURL).subscribe(
            communities => {
                self.communities = communities;

                communities.forEach(_ => {
                    this.checkboxes.push(<CheckCommunity>{community : _, checked : false});
                });
        },
        error => this.handleError('System error retrieving communities', 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 getSelectedCommunities() : string[] {
        return this.checkboxes.filter(community => community.checked == true).map(checkedCommunity => checkedCommunity.community).map(res => res._id);
    }

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

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

    public confirmDeleteSelectedCommunities() {
        this.deleteConfirmationModal.ids = this.getSelectedCommunities();
        this.deleteConfirmationModal.showModal();
    }

    public confirmedDeleteCommunities(ids : string[]) {
        this._helpContentService.deleteCommunities(ids, this.properties.adminToolsAPIURL).subscribe(
            _ => this.deleteCommunitiesFromArray(ids),
            error => this.handleError('System error deleting the selected communities', error)
        );
    }

    public editCommunity(i : number) {
        let community : Community = this.checkboxes[i].community;
        this.formGroup.patchValue(community);
        this.updateModal.showModal();
    }

    public communitySavedSuccessfully(community: Community) {
        this.checkboxes.push(<CheckCommunity>{community : community, checked : false});
        console.info("checkboxes length: "+this.checkboxes.length);
        this.applyCheck(false);
    }

    public communityUpdatedSuccessfully(community : Community) {
        this.checkboxes.find(checkItem => checkItem.community._id==community._id).community = community;
        this.applyCheck(false);
    }

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

    public applyFilter() {
        this.checkboxes = [];
        this.communities.filter(item => this.filterCommunities(item)).forEach(
            _ => this.checkboxes.push(<CheckCommunity>{community: _, checked: false})
        );
    }

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

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