import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {ActivatedRoute, Router} from "@angular/router"; import {HelpContentService} from "../../services/help-content.service"; import {FormArray, FormBuilder, FormGroup, Validators} from "@angular/forms"; import {CheckDivId, DivId} from "../../utils/entities/adminTool/divId"; import {Page} from "../../utils/entities/adminTool/page"; import {EnvProperties} from '../../utils/properties/env-properties'; import {Session} from '../../login/utils/helper.class'; import {LoginErrorCodes} from '../../login/utils/guardHelper.class'; import {HelperFunctions} from "../../utils/HelperFunctions.class"; import {Subscriber} from "rxjs"; import {properties} from "../../../../environments/environment"; import {PortalUtils} from "../portal/portalHelper"; import {AlertModal} from "../../utils/modal/alert"; import {Option} from "../../sharedComponents/input/input.component"; import {SearchInputComponent} from "../../sharedComponents/search-input/search-input.component"; declare var UIkit; @Component({ selector: 'divIds', templateUrl: './divIds.component.html', }) export class DivIdsComponent implements OnInit { @ViewChild('editModal') editModal: AlertModal; @ViewChild('deleteModal') deleteModal: AlertModal; private selectedDivIds: string[] = []; public checkboxes: CheckDivId[] = []; public divIds: DivId[] = []; public classForm: FormGroup; public pagesCtrl: FormArray; private searchText: RegExp = new RegExp(''); public keyword: string = ""; public properties: EnvProperties = properties; public formPages: Page[] = []; public showLoading: boolean = true; public errorMessage: string = ''; public updateErrorMessage: string = ''; public modalErrorMessage: string = ''; public filterForm: FormGroup; private subscriptions: any[] = []; public allPages: Option[] = []; @ViewChild('PageInput') pageInput: ElementRef; selectedCommunityPid = null; public portalUtils:PortalUtils = new PortalUtils(); private index: number; public selectedKeyword: string; @ViewChild('searchInputComponent') searchInputComponent: SearchInputComponent; ngOnInit() { this.filterForm = this._fb.group({ keyword: [''], type: ['all', Validators.required]}); this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => { this.searchText = new RegExp(value, 'i'); this.applyFilters(); })); this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => { this.applyFilters(); })); this.getDivIds(); this.subscriptions.push(this.route.queryParams.subscribe(params => { HelperFunctions.scroll(); this.selectedCommunityPid = params['communityId']; this.getPages(); })); } constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router, private _helpContentService: HelpContentService, private _fb: FormBuilder) { } ngOnDestroy(): void { this.subscriptions.forEach(value => { if (value instanceof Subscriber) { value.unsubscribe(); } else if (value instanceof Function) { value(); } }); } 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.subscriptions.push(this._helpContentService.getAllDivIdsFull( this.properties.adminToolsAPIURL).subscribe( divIds => { this.divIds = divIds; this.checkboxes = []; let self = this; divIds.forEach(_ => { self.checkboxes.push({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.divIds.findIndex(_ => _._id == id); this.divIds.splice(i, 1); } this.applyFilters(); } public confirmDeleteDivId(id: string) { this.selectedDivIds = [id]; this.confirmModalOpen(); } public confirmDeleteSelectedDivIds() { 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.deleteModal.cancelButton = true; this.deleteModal.okButton = true; this.deleteModal.alertTitle = "Delete Confirmation"; this.deleteModal.message = "Are you sure you want to delete the selected class(es)?"; this.deleteModal.okButtonText = "Yes"; this.deleteModal.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.subscriptions.push(this._helpContentService.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe( _ => { this.deleteDivIdsFromArray(this.selectedDivIds); UIkit.notification('Classes have been successfully deleted', { status: 'success', timeout: 6000, pos: 'bottom-right' }); 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.index = this.divIds.findIndex(value => value._id === divId._id); this.formPages = divId.pages; this.pagesCtrl = this._fb.array([], Validators.required); this.classForm = this._fb.group({ _id: this._fb.control(divId._id), name: this._fb.control(divId.name, Validators.required), pages: this.pagesCtrl, portalType: this._fb.control(divId.portalType, Validators.required) }); this.classForm.get('portalType').disable(); for(let i = 0; i < divId.pages.length; i++) { this.pagesCtrl.push(this._fb.control(divId.pages[i])); } this.divIdsModalOpen("Edit class", "Save Changes"); } public newDivId() { this.pagesCtrl = this._fb.array([], Validators.required); if(this.classForm) { this.classForm.get('portalType').enable(); } this.classForm = this._fb.group({ _id: this._fb.control(null), name: this._fb.control('', Validators.required), pages: this.pagesCtrl, portalType: this._fb.control('', Validators.required) }); this.modalErrorMessage = ""; this.divIdsModalOpen("Create class", "Create"); } private divIdsModalOpen(title: string, yesBtn: string) { if (!Session.isLoggedIn()) { this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url } }); } else { this.editModal.cancelButton = true; this.editModal.okButton = true; this.editModal.okButtonLeft = false; this.editModal.alertTitle = title; this.editModal.okButtonText = yesBtn; this.editModal.open(); } } public divIdSaveConfirmed(data: any) { this.showLoading = true; if (!Session.isLoggedIn()) { this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl": this._router.url } }); } else { if (!this.classForm.value._id) { this.modalErrorMessage = ""; this.subscriptions.push(this._helpContentService.saveDivId(this.classForm.value, this.properties.adminToolsAPIURL).subscribe( divId => { this.divIdSavedSuccessfully(divId); UIkit.notification('Class ' + divId.name + ' has been successfully created', { status: 'success', timeout: 6000, pos: 'bottom-right' }); }, error => this.handleUpdateError("System error creating class", error) )); } else { this.classForm.get('portalType').enable(); this.subscriptions.push(this._helpContentService.updateDivId(this.classForm.value, this.properties.adminToolsAPIURL).subscribe( divId => { this.divIdUpdatedSuccessfully(divId); UIkit.notification('Class ' + divId.name + ' has been successfully updated', { status: 'success', timeout: 6000, pos: 'bottom-right' }); }, error => this.handleUpdateError("System error updating class", error) )); } } } public divIdSavedSuccessfully(divId: DivId) { this.divIds.push(divId); this.applyFilters(); this.applyCheck(false); this.showLoading = false; } public divIdUpdatedSuccessfully(divId: DivId) { this.divIds[this.index] = divId; this.applyFilters(); this.applyCheck(false); this.showLoading = false; } public applyFilters() { this.checkboxes = []; this.divIds.filter(item => this.filterByType(item)).forEach( item => this.checkboxes.push({divId: item, checked: false}) ); this.checkboxes = this.checkboxes.filter(item => this.filterDivIds(item.divId)); } public filterByType(divId: DivId): boolean { let type = this.filterForm.get("type").value; return type == "all" || (type == divId.portalType); } public filterDivIds(divId: DivId): boolean { let textFlag = this.searchText.toString() == '' || (divId.name + ' ' + divId.portalType).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); } UIkit.notification('An error has occurred. Please try again later', { status: 'danger', timeout: 6000, pos: 'bottom-right' }); this.showLoading = false; } handleError(message: string, error) { this.errorMessage = message; console.log('Server responded: ' + error); this.showLoading = false; } getPages() { this.showLoading = true; this.errorMessage = ""; this.subscriptions.push(this._helpContentService.getAllPages(this.properties.adminToolsAPIURL).subscribe( pages => { this.allPages = []; pages.forEach(page => { this.allPages.push({ label: page.name, value: page }); }); this.showLoading = false; }, error => this.handleError('System error retrieving pages', error) )); } public onSearchClose() { this.selectedKeyword = this.filterForm.get('keyword').value; } public reset() { this.selectedKeyword = null; this.searchInputComponent.reset() } }