import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { HelpContentService } from '../../services/help-content.service';
import { FormGroup } from '@angular/forms';
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';
import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
import {UserManagementService} from '../../openaireLibrary/services/user-management.service';
import {Title} from '@angular/platform-browser';

@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('AlertModalSaveEntity') alertModalSaveEntity;
    @ViewChild('AlertModalUpdateEntity') alertModalUpdateEntity;
    @ViewChild('AlertModalDeleteEntities') alertModalDeleteEntities;
    private selectedEntities: string[] = [];

    @ViewChild(EntityFormComponent)
    public formComponent: EntityFormComponent;

    public checkboxes: CheckEntity[] = [];

    public entities: Entity[] = [];

    public formGroup: FormGroup;

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

    public communities: Community[] = [];
    public selectedCommunityPid: string;

    @ViewChild('AlertModalRelatedPages') alertModalRelatedPages;

    public toggleIds: string[];
    public toggleStatus: boolean;
    public properties: EnvProperties = null;

    public showLoading = true;
    public errorMessage = '';
    public updateErrorMessage = '';
    public modalErrorMessage = '';
    public isPortalAdministrator = null;

  constructor(private element: ElementRef, private route: ActivatedRoute,
              private _router: Router, private title: Title,
              private _helpContentService: HelpContentService,
              private userManagementService: UserManagementService) {}

    ngOnInit() {
      this.formGroup = this.formComponent.form;
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
           this.title.setTitle('Administration Dashboard | Entities');
           this.route.queryParams.subscribe(params => {
             HelperFunctions.scroll();
            this.userManagementService.getUserInfo().subscribe( user => {
              this.selectedCommunityPid = params['communityId'];
              this.applyCommunityFilter(this.selectedCommunityPid);
              this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.selectedCommunityPid;
            });
           });
      });

    }

    getEntities(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 = '';
        if(community_pid) {
          this._helpContentService.getCommunityEntities(community_pid, this.properties.adminToolsAPIURL).subscribe(
            entities => {
              this.entities = entities;
              this.checkboxes = [];

              let self = this;
              entities.forEach(_ => {
                self.checkboxes.push(<CheckEntity>{entity: _, checked: false});
              });

              this.showLoading = false;
            },
            error => this.handleError('System error retrieving entities', error));
        } else {
          this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
            entities => {
              this.entities = entities;
              this.checkboxes = [];

              let self = this;
              entities.forEach(_ => {
                self.checkboxes.push(<CheckEntity>{entity: _, checked: false});
              });
              this.showLoading = false;
            },
            error => this.handleError('System error retrieving community entities', error));
        }
      }
    }

    public toggleCheckBoxes(event) {
        this.checkboxes.forEach(_ => _.checked = event.target.checked);
    }

    public applyCheck(flag: boolean) {
        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) {
            const i = this.checkboxes.findIndex(_ => _.entity._id === id);
            this.checkboxes.splice(i, 1);
        }
    }

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

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

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

    public confirmedDeleteEntities(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._helpContentService.deleteEntities(this.selectedEntities, this.properties.adminToolsAPIURL).subscribe(
            _ => {
              this.deleteEntitiesFromArray(this.selectedEntities);
              this.showLoading = false;
            },
            error => this.handleUpdateError('System error deleting the selected entities', error)
        );
      }
    }

    public editEntity(i: number) {
        const entity: Entity = this.checkboxes[i].entity;
        this.formGroup.patchValue(entity);
        // this.updateModal.showModal();
        this.modalErrorMessage = '';
        this.entitiesModalOpen(this.alertModalUpdateEntity, 'Update', 'Update Entity');
    }

    public newEntity() {
        this.formComponent.reset();
        this.modalErrorMessage = '';
        this.entitiesModalOpen(this.alertModalSaveEntity, 'Save', 'Add a new Entity');
    }

    private entitiesModalOpen(modal: any, title: string, yesBtn: string) {
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'],
            { queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
      } else {
        modal.cancelButton = true;
        modal.okButton = true;
        modal.alertTitle = title;
        modal.okButtonText = yesBtn;
        modal.open();
      }
    }

    public entitySaveConfirmed(data: any) {
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'],
            { queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
      } else {
        if (!this.formGroup.valid) {
          this.entitiesModalOpen(this.alertModalSaveEntity, 'Save', 'Add a new Entity');
          this.modalErrorMessage = 'Please fill in all required fields marked with *';
        } else {
          this.modalErrorMessage = '';
          this._helpContentService.saveEntity(<Entity> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
              entity => {
                this.entitySavedSuccessfully(entity);
              },
              error => this.handleUpdateError('System error creating entity', error)
          );
        }
      }
    }

    public entityUpdateConfirmed(data: any) {
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'],
            { queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
      } else {
        if(!this.formGroup.valid) {
          this.entitiesModalOpen(this.alertModalUpdateEntity, 'Update', 'Update Entity');
          this.modalErrorMessage = 'Please fill in all required fields marked with *';
        } else {
          this._helpContentService.updateEntity(
              <Entity> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
              entity => {
                this.entityUpdatedSuccessfully(entity);
              },
              error => this.handleUpdateError('System error updating entity', error)
          );
        }
      }
    }

    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 {
        const textFlag = this.searchText.toString() === '' || (entity.name).match(this.searchText) != null;
        return textFlag;
    }

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

        this.showLoading = false;
    }

    handleUpdateError(message: string, error) {
        if (error == null) {
            this.formComponent.reset();
        } else {
          this.updateErrorMessage = message;
          console.log('Server responded: ' + error);
        }

        this.showLoading = false;
    }

    public applyCommunityFilter(community_pid: string) {
        this.getEntities(community_pid);
    }

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

    private confirmRelatedPagesModalOpen() {
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'],
            { queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
      } else {
        this.alertModalRelatedPages.cancelButton = true;
        this.alertModalRelatedPages.okButton = true;
        this.alertModalRelatedPages.alertTitle = 'Warning';
        this.alertModalRelatedPages.message = "This action will affect all search pages related to this entity! Pages' status will change to entity's status! Do you want to continue?";
        this.alertModalRelatedPages.okButtonText = 'Yes';
        this.alertModalRelatedPages.open();
      }
    }

    public continueToggling(event: any) {
      if (!Session.isLoggedIn()) {
        this._router.navigate(['/user-info'],
            { queryParams: { 'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl':  this._router.url} });
      } else {
        this.updateErrorMessage = '';
        this._helpContentService.toggleEntities(
            this.selectedCommunityPid, this.toggleIds, this.toggleStatus, this.properties.adminToolsAPIURL).subscribe(
            () => {
              for (let id of this.toggleIds) {
                const i = this.checkboxes.findIndex(_ => _.entity._id === id);
                this.checkboxes[i].entity.isEnabled = this.toggleStatus;
              }
              this.applyCheck(false);
            },
            error => this.handleUpdateError('System error changing the status of the selected entity(-ies)', error)
        );
      }
    }
  }
