import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HelpContentService} from '../../services/help-content.service';
import {UntypedFormBuilder, UntypedFormGroup, Validators} from '@angular/forms';
import {EnvProperties} from '../../utils/properties/env-properties';
import {HelperFunctions} from "../../utils/HelperFunctions.class";
import {Subscriber} from "rxjs";
import {CheckPortal, Portal} from "../../utils/entities/adminTool/portal";
import {PortalUtils} from "./portalHelper";
import {properties} from "../../../../environments/environment";
import {AlertModal} from "../../utils/modal/alert";
import {Title} from "@angular/platform-browser";
import {ClearCacheService} from "../../services/clear-cache.service";
import {NotificationHandler} from "../../utils/notification-handler";

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

export class PortalsComponent implements OnInit {
  
  @ViewChild('editModal') editModal: AlertModal;
  @ViewChild('deleteModal') deleteModal: AlertModal;
  private selectedPortals: string[] = [];
  
  public checkboxes: CheckPortal[] = [];
  public portals: Portal[] = [];
  
  public portalForm: UntypedFormGroup;
  public filterForm: UntypedFormGroup;
  private subscriptions: any[] = [];
  
  private searchText: RegExp = new RegExp('');
  public keyword = '';
  
  public properties: EnvProperties = null;
  
  public showLoading = true;
  public portalUtils: PortalUtils = new PortalUtils();
  private index: number;
  
  constructor(private element: ElementRef, private route: ActivatedRoute,
              private title: Title,
              private _router: Router, private _helpContentService: HelpContentService, private _fb: UntypedFormBuilder,
              private _clearCacheService: ClearCacheService) {
  }
  
  ngOnInit() {
    this.title.setTitle('Administrator Dashboard | Portals');
    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();
    }));
    
    HelperFunctions.scroll();
    this.properties = properties;
    this.getPortals();
    
  }
  
  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }
  
  getPortals() {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.getPortalsFull(this.properties.adminToolsAPIURL).subscribe(
      portals => {
        this.portals = portals;
        if (portals) {
          portals.forEach(_ => {
            this.checkboxes.push(<CheckPortal>{portal: _, checked: false});
          });
        }
        this.showLoading = false;
      },
      error => this.handleError('System error retrieving portals', error)));
  }
  
  public toggleCheckBoxes(event) {
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
  }
  
  public applyCheck(flag: boolean) {
    this.checkboxes.forEach(_ => _.checked = flag);
  }
  
  public getSelectedPortals(): string[] {
    return this.checkboxes.filter(portal => portal.checked === true).map(checkedPortal => checkedPortal.portal).map(res => res._id);
  }
  
  private deletePortalsFromArray(ids: string[]): void {
    for (let id of ids) {
      let i = this.portals.findIndex(_ => _._id == id);
      this.portals.splice(i, 1);
    }
    this.applyFilters();
  }
  
  public confirmDeletePortal(id: string) {
    // this.deleteConfirmationModal.ids = [id];
    // this.deleteConfirmationModal.showModal();
    this.selectedPortals = [id];
    this.confirmModalOpen();
  }
  
  public confirmDeleteSelectedPortals() {
    this.selectedPortals = this.getSelectedPortals();
    this.confirmModalOpen();
  }
  
  private confirmModalOpen() {
      this.deleteModal.alertTitle = 'Delete Confirmation';
      this.deleteModal.message = 'Are you sure you want to delete the selected portal(s)?';
      this.deleteModal.okButtonText = 'Yes';
      this.deleteModal.open();
  }
  
  public confirmedDeletePortals(data: any) {
      this.showLoading = true;
      this.subscriptions.push(this._helpContentService.deleteCommunities(this.selectedPortals, this.properties.adminToolsAPIURL).subscribe(
        _ => {
          this.deletePortalsFromArray(this.selectedPortals);
          NotificationHandler.rise('Portals have been <b>successfully deleted</b>');
          this.showLoading = false;
         // this._clearCacheService.clearCache("Portals deleted");
        },
        error => this.handleUpdateError('System error deleting the selected communities', error)
      ));
  }
  
  public editPortal(i: number) {
    const portal: Portal = this.checkboxes[i].portal;
    this.index = this.portals.findIndex(value => value._id === portal._id);
    this.portalForm = this._fb.group({
      _id: this._fb.control(portal._id),
      name: this._fb.control(portal.name, Validators.required),
      pid: this._fb.control(portal.pid, Validators.required),
      piwik: this._fb.control(portal.piwik),
			twitterAccount: this._fb.control(portal.twitterAccount),
      type: this._fb.control(portal.type, Validators.required),
    });
    this.portalForm.get('type').disable();
    this.portalModalOpen('Edit Portal', 'Save');
  }
  
  public newPortal() {
    if(this.portalForm) {
      this.portalForm.get('type').enable();
    }
    this.portalForm = this._fb.group({
      _id: this._fb.control(''),
      name: this._fb.control('', Validators.required),
      pid: this._fb.control('', Validators.required),
      piwik: this._fb.control(''),
			twitterAccount: this._fb.control(''),
      type: this._fb.control('', Validators.required),
    });
    this.portalModalOpen('Create Portal', 'Create');
  }
  
  private portalModalOpen(title: string, yesBtn: string) {
    this.editModal.okButtonLeft = false;
    this.editModal.alertTitle = title;
    this.editModal.okButtonText = yesBtn;
    this.editModal.open();
  }
  
  public portalSaveConfirmed(data: any) {
    this.showLoading = true;
    if (this.portalForm.getRawValue()._id) {
      this.subscriptions.push(this._helpContentService.updateCommunity(<Portal>this.portalForm.getRawValue(),
        this.properties.adminToolsAPIURL).subscribe(
        portal => {
          this.portalUpdatedSuccessfully(portal);
          NotificationHandler.rise('Portal <b>' + portal.name + '</b> has been <b>successfully updated</b>');
          //this._clearCacheService.clearCache("Portal updated");
        },
        error => this.handleUpdateError('System error updating portal', error)
      ));
    } else {
      this.subscriptions.push(this._helpContentService.saveCommunity(<Portal>this.portalForm.getRawValue(),
        this.properties.adminToolsAPIURL).subscribe(
        portal => {
          this.portalSavedSuccessfully(portal);
          NotificationHandler.rise('Portal <b>' + portal.name + '</b> has been <b>successfully created</b>');
          //this._clearCacheService.clearCache("Portal saved");
        },
        error => this.handleUpdateError('System error creating portal', error)
      ));
    }
  }
  
  public portalSavedSuccessfully(portal: Portal) {
    this.portals.push(portal);
    this.applyFilters();
    this.applyCheck(false);
    this.showLoading = false;
  }
  
  public portalUpdatedSuccessfully(portal: Portal) {
    this.portals[this.index] = portal;
    this.applyFilters();
    this.applyCheck(false);
    this.showLoading = false;
  }
  
  public applyFilters() {
    this.checkboxes = [];
    this.portals.filter(item => this.filterByType(item)).forEach(
      _ => this.checkboxes.push(<CheckPortal>{portal: _, checked: false})
    );
    this.checkboxes = this.checkboxes.filter(item => this.filterPortals(item.portal));
  }
  
  public filterByType(portal: Portal): boolean {
    let type = this.filterForm.get("type").value;
    return type == "all" || (type === portal.type);
  }
  
  public filterPortals(portal: Portal): boolean {
    return this.searchText.toString() === '' || (portal.name + portal.type + portal.pid).match(this.searchText) != null;
  }
  
  handleUpdateError(message: string, error = null) {
    if (!error) {
      this.portalForm = this._fb.group({
        name: '',
        _id: '',
        pid: '',
        piwik: '',
        type: ''
      });
    } else {
      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;
  }
}
