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 { EntityFormComponent } from "./entity-form.component";
import { CheckEntity, Entity } from "../../domain/entity";
import { Community } from "../../domain/community";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

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

export class EntitiesComponent implements OnInit {

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

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

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

    @ViewChild(EntityFormComponent)
    public formComponent : EntityFormComponent;

    public checkboxes : CheckEntity[] = [];

    public entities : Entity[] = [];

    public errorMessage: string;

    public formGroup : FormGroup;

    private searchText : RegExp = new RegExp('');

    public communities: Community[] = [];

    public selectedCommunityPid: string;
    @ViewChild('okModal')
    public okModal:ModalFormComponent;
public toggleIds: string[];
public toggleStatus: boolean;
public properties:EnvProperties = null;

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

    }

    constructor(private route: ActivatedRoute, private _helpContentService: HelpContentService) {}

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

    getEntities(community_pid: string) {
        let self = this;
        this._helpContentService.getCommunityEntities(community_pid, this.properties.adminToolsAPIURL).subscribe(
            entities => {
                self.entities = entities;
                self.checkboxes = [];

                entities.forEach(_ => {
                    self.checkboxes.push(<CheckEntity>{entity : _, checked : false});
                });
        },
        error => this.handleError('System error retrieving entities', 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 getSelectedEntities() : string[] {
        return this.checkboxes.filter(entity => entity.checked == true).map(checkedEntity => checkedEntity.entity).map(res => res._id);
    }

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

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

    public confirmDeleteSelectedEntities() {
        this.deleteConfirmationModal.ids = this.getSelectedEntities();
        this.deleteConfirmationModal.showModal();
    }

    public confirmedDeleteEntities(ids : string[]) {
        this._helpContentService.deleteEntities(ids, this.properties.adminToolsAPIURL).subscribe(
            _ => this.deleteEntitiesFromArray(ids),
            error => this.handleError('System error deleting the selected entities', error)
        );
    }

    public editEntity(i : number) {
        let entity : Entity = this.checkboxes[i].entity;
        this.formGroup.patchValue(entity);
        this.updateModal.showModal();
    }

    public entitySavedSuccessfully(entity: Entity) {
        this.checkboxes.push(<CheckEntity>{entity : entity, checked : false});
        this.applyCheck(false);
    }

    public entityUpdatedSuccessfully(entity : Entity) {
        this.checkboxes.find(checkItem => checkItem.entity._id==entity._id).entity = entity;
        this.applyCheck(false);
    }

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

    public applyFilter() {
        this.checkboxes = [];
        this.entities.filter(item => this.filterEntities(item)).forEach(
            _ => this.checkboxes.push(<CheckEntity>{entity: _, checked: false})
        );
    }

    public filterEntities(entity : Entity) : boolean {
        let textFlag = this.searchText.toString() == '' || (entity.name).match(this.searchText) != null;
        return textFlag;
    }

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

    public toggleEntities(status : boolean, ids : string[]) {
        this.okModal.showModal();
        this.toggleIds = ids;
        this.toggleStatus = status;
    }

    public continueToggling(event: any) {
      this._helpContentService.toggleEntities(this.selectedCommunityPid,this.toggleIds,this.toggleStatus, this.properties.adminToolsAPIURL).subscribe(
          () => {
            for(let id of this.toggleIds) {
              let i = this.checkboxes.findIndex(_ => _.entity._id == id);
              this.checkboxes[i].entity.isEnabled=this.toggleStatus;
            }
            this.applyCheck(false);
          },
          error => this.handleError('System error changing the status of the selected entity(-ies)', error)
      );
    }

  }
