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 { DivIdFormComponent } from "./divId-form.component";
import { CheckDivId, DivId } from "../../domain/divId";
//import { Community } from "../../domain/community";
import { Page } from "../../domain/page";
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 {Title} from '@angular/platform-browser';

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

export class DivIdsComponent implements OnInit {

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

    // @ViewChild('deleteConfirmationModal')
    // public deleteConfirmationModal : DeleteConfirmationDialogComponent;
    @ViewChild('AlertModalSaveDivId') alertModalSaveDivId;
    @ViewChild('AlertModalUpdateDivId') alertModalUpdateDivId;
    @ViewChild('AlertModalDeleteDivIds') alertModalDeleteDivIds;
    private selectedDivIds: string[] = [];

    @ViewChild(DivIdFormComponent)
    public formComponent : DivIdFormComponent;

    public checkboxes : CheckDivId[] = [];

    public divIds : DivId[] = [];

    //public errorMessage: string;

    public formGroup : FormGroup;

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

    public pages: Page[] = [];
    public properties:EnvProperties = null;
    public formPages: Page[] = [];

    public showLoading: boolean = true;
    public errorMessage: string = '';
    public updateErrorMessage: string = '';
    public modalErrorMessage: string = '';

    ngOnInit() {
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
          HelperFunctions.scroll();
           this.title.setTitle('Administration Dashboard | Classes');
           this.properties = data.envSpecific;
           this.formGroup = this.formComponent.form;

           this.getDivIds();
      });
    }

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

    getDivIds() {
      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._helpContentService.getDivIdsFull(null, this.properties.adminToolsAPIURL).subscribe(
            divIds => {
                this.divIds = divIds;
                this.checkboxes = [];

                let self = this;
                divIds.forEach(_ => {
                    self.checkboxes.push(<CheckDivId>{divId : _, checked : false});
                });

                this.showLoading = false;
        },
        error => this.handleError('System error retrieving classes', error));
      }
    }

    // public showModal():void {
    //     this.modal.showModal();
    // }

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

    public applyCheck(flag : boolean) {
        this.checkboxes.forEach(_ => _.checked = flag);
    }

    public getSelectedDivIds() : string[] {
        return this.checkboxes.filter(divId => divId.checked == true).map(checkedDivId => checkedDivId.divId).map(res => res._id);
    }

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

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

    public confirmDeleteSelectedDivIds() {
        //this.deleteConfirmationModal.ids = this.getSelectedDivIds();
        //this.deleteConfirmationModal.showModal();
        this.selectedDivIds = this.getSelectedDivIds();
        this.confirmModalOpen();
    }

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

    public confirmedDeleteDivIds(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.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe(
           _ => {
             this.deleteDivIdsFromArray(this.selectedDivIds);
             this.showLoading = false;
           },
           error => this.handleUpdateError('System error deleting the selected classes', error)
        );
      }
    }

    public editDivId(i : number) {
        let divId : DivId = this.checkboxes[i].divId;
        this.formPages = <Page[]>divId.pages;

        /*let pageIds: string[] = [];
        let index = 0;
        for(let page of <Page[]>divId.pages) {
          pageIds[index] = page._id;
          index++;
        }*/

        this.formGroup.patchValue(divId);
        this.formComponent.setPages(divId.pages as Page[]);//pageIds);

        //this.updateModal.showModal();
        this.divIdsModalOpen(this.alertModalUpdateDivId, "Update", "Update Class");
    }

    public newDivId() {
        this.formComponent.reset();
        this.modalErrorMessage = "";
        this.divIdsModalOpen(this.alertModalSaveDivId, "Save", "Add a new Class");
    }

    private divIdsModalOpen(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 divIdSaveConfirmed(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.divIdsModalOpen(this.alertModalSaveDivId, "Save", "Add a new Class");
          this.modalErrorMessage = "Please fill in all required fields marked with *";
        } else {
          this.modalErrorMessage = "";
          this._helpContentService.saveDivId(<DivId> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
              divId => {
                this.divIdSavedSuccessfully(divId);
              },
              error => this.handleUpdateError("System error creating class", error)
          );
        }
      }
    }

    public divIdUpdateConfirmed(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.divIdsModalOpen(this.alertModalUpdateDivId, "Update", "Update Class");
          this.modalErrorMessage = "Please fill in all required fields marked with *";
        } else {
          this._helpContentService.updateDivId(<DivId> this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
              divId => {
                this.divIdUpdatedSuccessfully(divId);
              },
              error => this.handleUpdateError("System error updating class", error)
          );
        }
      }
    }

    public divIdSavedSuccessfully(divId: DivId) {
        this.checkboxes.push(<CheckDivId>{divId : divId, checked : false});
        this.applyCheck(false);
    }

    public divIdUpdatedSuccessfully(divId : DivId) {
        this.checkboxes.find(checkItem => checkItem.divId._id==divId._id).divId = divId;
        this.applyCheck(false);
    }

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

    public applyFilter() {
        this.checkboxes = [];
        this.divIds.filter(item => this.filterDivIds(item)).forEach(
            _ => this.checkboxes.push(<CheckDivId>{divId: _, checked: false})
        );
    }

    public filterDivIds(divId : DivId) : boolean {
        let textFlag = this.searchText.toString() == '' || (divId.name).match(this.searchText) != null;
        return textFlag;
    }

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

        this.showLoading = false;
    }

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

        this.showLoading = false;
    }
}
