import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from "@angular/router";
import {HelpContentService} from "../../services/help-content.service";
import {UntypedFormArray, UntypedFormBuilder, UntypedFormGroup, 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 {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 {Title} from "@angular/platform-browser";
import {ClearCacheService} from "../../services/clear-cache.service";
import {NotificationHandler} from "../../utils/notification-handler";

@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: UntypedFormGroup;
  public pagesCtrl: UntypedFormArray;
  
  private searchText: RegExp = new RegExp('');
  public keyword: string = "";
  public properties: EnvProperties = properties;
  public formPages: Page[] = [];
  public showLoading: boolean = true;
  public filterForm: UntypedFormGroup;
  private subscriptions: any[] = [];
  public allPages: Option[] = [];
  selectedCommunityPid = null;
  public portalUtils: PortalUtils = new PortalUtils();
  private index: number;
  
  constructor(private element: ElementRef, private route: ActivatedRoute, private _router: Router,
              private title: Title,
              private _helpContentService: HelpContentService, private _fb: UntypedFormBuilder,
              private _clearCacheService: ClearCacheService) {
  }
  
  ngOnInit() {
    this.title.setTitle('Administrator Dashboard | Classes');
    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();
    }));
    
  }
  
  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }
  
  getDivIds() {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getAllDivIdsFull(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.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() {
    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) {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.deleteDivIds(this.selectedDivIds, this.properties.adminToolsAPIURL).subscribe(
      _ => {
        this.deleteDivIdsFromArray(this.selectedDivIds);
        NotificationHandler.rise('Classes have been <b>successfully deleted</b>');
        this.showLoading = false;
        //this._clearCacheService.clearCache("Class ids deleted");
      },
      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 = <Page[]>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.divIdsModalOpen("Create class", "Create");
  }
  
  private divIdsModalOpen(title: string, yesBtn: string) {
    this.editModal.okButtonLeft = false;
    this.editModal.alertTitle = title;
    this.editModal.okButtonText = yesBtn;
    this.editModal.open();
  }
  
  public divIdSaveConfirmed(data: any) {
    this.showLoading = true;
    if (!this.classForm.getRawValue()._id) {
      this.subscriptions.push(this._helpContentService.saveDivId(<DivId>this.classForm.getRawValue(), this.properties.adminToolsAPIURL).subscribe(
        divId => {
          this.divIdSavedSuccessfully(divId);
          NotificationHandler.rise('Class <b>' + divId.name + '</b> has been <b>successfully created</b>');
          //this._clearCacheService.clearCache("Class id saved");
        },
        error => this.handleUpdateError("System error creating class", error)
      ));
    } else {
      this.subscriptions.push(this._helpContentService.updateDivId(<DivId>this.classForm.getRawValue(), this.properties.adminToolsAPIURL).subscribe(
        divId => {
          this.divIdUpdatedSuccessfully(divId);
          NotificationHandler.rise('Class <b>' + divId.name + '</b> has been <b>successfully updated</b>');
          //this._clearCacheService.clearCache("Class id updated");
        },
        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(<CheckDivId>{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 {
    return this.searchText.toString() == '' || (divId.name + ' ' + divId.portalType).match(this.searchText) != null;
  }
  
  handleUpdateError(message: string, error = null) {
    if (error) {
      console.log('Server responded: ' + error);
    }
    NotificationHandler.rise(message,'danger');
    this.showLoading = false;
  }
  
  handleError(message: string, error = null) {
    if (error) {
      console.log('Server responded: ' + error);
    }
    NotificationHandler.rise(message,'danger');
    this.showLoading = false;
  }
  
  getPages() {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getAllPages(this.properties.adminToolsAPIURL).subscribe(
      pages => {
        this.allPages = [];
        pages.forEach(page => {
          this.allPages.push({
            label: page.name + " [" + page.portalType + "]",
            value: page
          });
        });
        this.showLoading = false;
      },
      error => this.handleError('System error retrieving pages', error)
    ));
  }
}
