import {Component, OnDestroy, OnInit, ViewChild} from "@angular/core";
import {StakeholderService} from "../../monitor/services/stakeholder.service";
import {Stakeholder, Visibility} from "../../monitor/entities/stakeholder";
import {zip} from "rxjs";
import {UntypedFormBuilder, UntypedFormGroup} from "@angular/forms";
import {AlertModal} from "../../utils/modal/alert";
import {Option} from "../../sharedComponents/input/input.component";
import {Title} from "@angular/platform-browser";
import {UserManagementService} from "../../services/user-management.service";
import {Session} from "../../login/utils/helper.class";
import {EditStakeholderComponent} from "../general/edit-stakeholder/edit-stakeholder.component";
import {ActivatedRoute} from "@angular/router";
import {CacheIndicatorsService} from "../utils/cache-indicators/cache-indicators.service";
import {NotificationHandler} from "../../utils/notification-handler";
import {StakeholderBaseComponent} from "../utils/stakeholder-base.component";

type Tab = 'all' | 'templates'| 'profiles';

declare var UIkit;

@Component({
  selector: 'home',
  templateUrl: "./manageStakeholders.component.html",
  styleUrls: ["./manageStakeholders.component.less"]
})
export class ManageStakeholdersComponent extends StakeholderBaseComponent implements OnInit, OnDestroy {
  public loading: boolean = true;
	public deleteLoading: boolean = false;
  public defaultStakeholders: Stakeholder[];
  public stakeholders: Stakeholder[];
  public alias: string[];
  public stakeholder: Stakeholder;
  public index: number;
  public user = null;
  public tab: Tab = 'all';
  public currentPage: number = 1;
  public currentTemplatesPage: number = 1;
  public pageSize: number = 15;
  public typeOptions: Option[];
  /**
   *  Filtered Stakeholders
   */
  public displayDefaultStakeholders: Stakeholder[] = [];
  public displayStakeholders: Stakeholder[] = [];
  /**
   * Top filters
   */
  public filters: UntypedFormGroup;
  public callback: Function;
  
  /**
   * Grid or List View
   */
  @ViewChild('editStakeholderModal', { static: true }) editStakeholderModal: AlertModal;
  @ViewChild('deleteStakeholderModal', { static: true }) deleteStakeholderModal: AlertModal;
  @ViewChild('editStakeholderComponent', { static: true }) editStakeholderComponent: EditStakeholderComponent;
  
  constructor(private stakeholderService: StakeholderService,
              private cacheIndicatorsService: CacheIndicatorsService,
              private userManagementService: UserManagementService,
              protected _route: ActivatedRoute,
              protected _title: Title,
              private fb: UntypedFormBuilder) {
    super();
  }
  
  ngOnInit(): void {
    this.typeOptions = [{value: 'all', label: 'All'}].concat(this.stakeholderUtils.types);
    this.buildFilters();
    this.title = 'Manage Profiles';
    this.setMetadata();
    this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
      this.user = user;
    }));
    let data = zip(
      this.stakeholderService.getDefaultStakeholders(this.properties.monitorServiceAPIURL),
      this.stakeholderService.getMyStakeholders(this.properties.monitorServiceAPIURL),
      this.stakeholderService.getAlias(this.properties.monitorServiceAPIURL)
    );
    this.subscriptions.push(data.subscribe(res => {
      this.defaultStakeholders = res[0];
      this.stakeholders = res[1];
      this.displayDefaultStakeholders = res[0];
      this.displayStakeholders = res[1];
      this.alias = res[2];
      this.loading = false;
    }, error => {
      this.loading = false;
    }));
  }
  
  hide(element: any) {
    UIkit.dropdown(element).hide();
  }
  
  private buildFilters() {
    this.filters = this.fb.group({
      status: this.fb.control('all'),
      type: this.fb.control('all'),
      keyword: this.fb.control('')
    });
    this.subscriptions.push(this.filters.get('status').valueChanges.subscribe(value => {
      this.filtering();
    }));
    this.subscriptions.push(this.filters.get('type').valueChanges.subscribe(value => {
      this.filtering();
    }));
    this.subscriptions.push(this.filters.get('keyword').valueChanges.subscribe(value => {
      this.filtering();
    }));
  }
  
  private filterByStatus(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (value === 'all') {
      return stakeholders;
    } else {
      return stakeholders.filter(stakeholder => stakeholder.visibility == value);
    }
  }

  private filterByType(stakeholders: Stakeholder[], value) {
    if(value == 'all') {
      return stakeholders;
    } else {
      return stakeholders.filter(item => item.type == value);
    }
  }
  
  private filterByKeyword(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (!value) {
      return stakeholders;
    } else {
      return stakeholders.filter(stakeholder =>
        stakeholder.name && stakeholder.name.toLowerCase().includes(value.toLowerCase()) ||
        stakeholder.type && stakeholder.type.toLowerCase().includes(value.toLowerCase()) ||
        stakeholder.index_id && stakeholder.index_id.toLowerCase().includes(value.toLowerCase()) ||
        stakeholder.index_shortName && stakeholder.index_shortName.toLowerCase().includes(value.toLowerCase()) ||
        stakeholder.index_name && stakeholder.index_name.toLowerCase().includes(value.toLowerCase())
      );
    }
  }

  filtering() {
    let keyword = this.filters.get('keyword').value;
    let type = this.filters.get('type').value;
    let status = this.filters.get('status').value;
    let displayStakeholders = this.stakeholders;
    let displayDefaultStakeholders = this.defaultStakeholders;

    displayStakeholders = this.filterByKeyword(displayStakeholders, keyword);
    displayStakeholders = this.filterByType(displayStakeholders, type);
    displayStakeholders = this.filterByStatus(displayStakeholders, status);
    displayDefaultStakeholders = this.filterByKeyword(displayDefaultStakeholders, keyword);
    displayDefaultStakeholders = this.filterByType(displayDefaultStakeholders, type);
    displayDefaultStakeholders = this.filterByStatus(displayDefaultStakeholders, status);

    this.displayStakeholders = displayStakeholders;
    this.displayDefaultStakeholders = displayDefaultStakeholders;
    this.currentPage = 1;
    this.currentTemplatesPage = 1;
  }
  
  public editStakeholder(stakeholder: Stakeholder = null, isDefault: boolean = false) {
    if (isDefault) {
      this.index = (stakeholder) ? this.defaultStakeholders.findIndex(value => value._id === stakeholder._id) : -1;
    } else {
      this.index = (stakeholder) ? this.stakeholders.findIndex(value => value._id === stakeholder._id) : -1;
    }
    if (!stakeholder) {
      this.stakeholder = new Stakeholder(null, null, null,
        null, null, null, null, null);
    } else {
      this.stakeholder = stakeholder;
    }
    this.editStakeholderComponent.init(this.stakeholder, this.alias, this.defaultStakeholders, isDefault, this.index === -1);
    if (this.index !== -1) {
      this.callback = (stakeholder: Stakeholder) => {
        let index: number;
        if (stakeholder.defaultId == null) {
          index = this.alias.findIndex(value => value == this.defaultStakeholders[this.index].alias);
          this.defaultStakeholders[this.index] = stakeholder;
        } else {
          index = this.alias.findIndex(value => value == this.stakeholders[this.index].alias);
          this.stakeholders[this.index] = stakeholder;
        }
        if(index != -1) {
          this.alias[index] = stakeholder.alias;
        }
				this.editStakeholderModal.cancel();
      };
      this.editStakeholderModal.alertTitle = 'Edit ' + this.stakeholder.name;
      this.editStakeholderModal.okButtonText = 'Save Changes';
    } else {
      this.callback = (stakeholder: Stakeholder) => {
        if (stakeholder.defaultId === null) {
          this.defaultStakeholders.push(stakeholder);
        } else {
          this.stakeholders.push(stakeholder);
        }
        this.alias.push(stakeholder.alias);
				this.editStakeholderModal.cancel();
        this.filtering();
      };
      this.editStakeholderModal.alertTitle = 'Create a new ' + (isDefault?'Default ':'') + 'Profile';
      this.editStakeholderModal.okButtonText = 'Create';
    }
    this.editStakeholderModal.cancelButtonText = 'Cancel';
    this.editStakeholderModal.okButtonLeft = false;
    this.editStakeholderModal.alertMessage = false;
		this.editStakeholderModal.stayOpen = true;
    this.editStakeholderModal.open();
  }
  
  public createReport(stakeholder: Stakeholder) {
    this.cacheIndicatorsService.createReport(stakeholder.alias).subscribe(report => {
      NotificationHandler.rise('A caching process for ' + stakeholder.name + ' has been started.' )
    }, error => {
      console.log(error);
      NotificationHandler.rise(error.message(), 'danger');
    });
  }
  
  public deleteStakeholderOpen(stakeholder: Stakeholder) {
    this.stakeholder = stakeholder;
    this.deleteStakeholderModal.alertTitle = 'Delete ' + this.stakeholder.index_name;
    this.deleteStakeholderModal.cancelButtonText = 'No';
    this.deleteStakeholderModal.okButtonText = 'Yes';
		this.deleteStakeholderModal.alertMessage = false;
		this.deleteStakeholderModal.stayOpen = true;
    this.deleteStakeholderModal.open();
  }
  
  public deleteStakeholder() {
		this.deleteLoading = true;
    if (!this.stakeholder.defaultId) {
      this.index = (this.stakeholder) ? this.defaultStakeholders.findIndex(value => value._id === this.stakeholder._id) : -1;
    } else {
      this.index = (this.stakeholder) ? this.stakeholders.findIndex(value => value._id === this.stakeholder._id) : -1;
    }
    this.subscriptions.push(this.stakeholderService.deleteElement(this.properties.monitorServiceAPIURL, [this.stakeholder._id]).subscribe(() => {
      UIkit.notification(this.stakeholder.name+ ' has been <b>successfully deleted</b>', {
        status: 'success',
        timeout: 6000,
        pos: 'bottom-right'
      });
      if (!this.stakeholder.defaultId) {
        this.defaultStakeholders.splice(this.index, 1);
      } else {
        this.stakeholders.splice(this.index, 1);
      }
      this.alias = this.alias.filter(item => item !== this.stakeholder.alias);
			this.deleteLoading = false;
			this.deleteStakeholderModal.cancel();
      this.filtering();
    }, error => {
      UIkit.notification('An error has occurred. Please try again later', {
        status: 'danger',
        timeout: 6000,
        pos: 'bottom-right'
      });
			this.deleteLoading = false;
			this.deleteStakeholderModal.cancel();
    }));
  }
  
  changeStakeholderStatus(stakeholder: Stakeholder, visibility: Visibility) {
    let path = [
      stakeholder._id
    ];
    this.subscriptions.push(this.stakeholderService.changeVisibility(this.properties.monitorServiceAPIURL, path, visibility).subscribe(returnedElement => {
      stakeholder.visibility = returnedElement.visibility;
      UIkit.notification(stakeholder.name+ '\'s status has been <b>successfully changed</b> to ' + stakeholder.visibility.toLowerCase(), {
        status: 'success',
        timeout: 6000,
        pos: 'bottom-right'
      });
    }, error => {
      UIkit.notification('An error has occurred. Please try again later', {
        status: 'danger',
        timeout: 6000,
        pos: 'bottom-right'
      });
    }));
  }
  
  public isManager(): boolean {
    return this.isCurator() || (Session.isKindOfMonitorManager(this.user));
  }
  
  public isProfileManager(stakeholder: Stakeholder): boolean {
    return this.isCurator() || (Session.isManager(stakeholder.type, stakeholder.alias, this.user));
  }
  
  public isCurator(): boolean {
    return this.isAdmin() || Session.isMonitorCurator(this.user);
  }
  
  public isAdmin(): boolean {
    return Session.isPortalAdministrator(this.user);
  }

  get typesAsString() {
    return this.stakeholderUtils.types.slice(0, this.stakeholderUtils.types.length - 1).map(type => type.label).join(', ') +
        ' or ' + this.stakeholderUtils.types[this.stakeholderUtils.types.length - 1].label
  }

  public updateCurrentPage($event) {
    this.currentPage = $event.value;
  }

  public updateCurrentTemplatesPage($event) {
    this.currentTemplatesPage = $event.value;
  }
}
