import {Component, OnDestroy, OnInit, ViewChild} from "@angular/core";
import {StakeholderService} from "../openaireLibrary/monitor/services/stakeholder.service";
import {EnvProperties} from "../openaireLibrary/utils/properties/env-properties";
import {EnvironmentSpecificService} from "../openaireLibrary/utils/properties/environment-specific.service";
import {Stakeholder, Visibility} from "../openaireLibrary/monitor/entities/stakeholder";
import {Subscriber, zip} from "rxjs";
import {StakeholderUtils} from "../utils/indicator-utils";
import {FormBuilder, FormGroup} from "@angular/forms";
import {AlertModal} from "../openaireLibrary/utils/modal/alert";
import {Option} from "../openaireLibrary/sharedComponents/input/input.component";
import {Title} from "@angular/platform-browser";
import {UserManagementService} from "../openaireLibrary/services/user-management.service";
import {Session} from "../openaireLibrary/login/utils/helper.class";
import {EditStakeholderComponent} from "../general/edit-stakeholder/edit-stakeholder.component";
import {properties} from "../../environments/environment";
import {ActivatedRoute} from "@angular/router";

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

declare var UIkit;

@Component({
  selector: 'home',
  templateUrl: "./manageStakeholders.component.html",
  styleUrls: ['manageStakeholders.component.css']
})
export class ManageStakeholdersComponent implements OnInit, OnDestroy {
  
  public properties: EnvProperties;
  public loading: boolean = true;
  public stakeholderUtils: StakeholderUtils = new StakeholderUtils();
  public defaultStakeholders: Stakeholder[];
  public stakeholders: Stakeholder[];
  public alias: string[];
  public stakeholder: Stakeholder;
  public index: number;
  public user = null;
  /**
   *  Filtered Stakeholders
   */
  public displayDefaultStakeholders: Stakeholder[];
  public displayStakeholders: Stakeholder[];
  /**
   * Top filters
   */
  public filters: FormGroup;
  public all: Option = {
    value: 'all',
    label: 'All'
  };
  
  public callback: Function;
  
  /**
   * Grid or List View
   */
  private subscriptions: any[] = [];
  @ViewChild('editStakeholderModal') editStakeholderModal: AlertModal;
  @ViewChild('deleteStakeholderModal') deleteStakeholderModal: AlertModal;
  @ViewChild('editStakeholderComponent') editStakeholderComponent: EditStakeholderComponent;
  
  tab: Tab = 'all';
  
  constructor(private stakeholderService: StakeholderService,
              private userManagementService: UserManagementService,
              private propertiesService: EnvironmentSpecificService,
              private route: ActivatedRoute,
              private title: Title,
              private fb: FormBuilder) {
  }
  
  ngOnInit(): void {
    this.subscriptions.push(this.route.fragment.subscribe((fragment: Tab) => {
      if (this.isTab(fragment)) {
        this.tab = fragment;
      } else {
        this.tab = 'all';
      }
    }));
    this.buildFilters();
    this.properties = properties;
    this.title.setTitle('Manage profiles');
    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;
    }));

    this.subscriptions.push(UIkit.util.on(document, 'hidden', '#edit_modal', (): void => {
      this.editStakeholderComponent.removePhoto();
    }));
  }
  
  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }
  
  hide(element: any) {
    UIkit.dropdown(element).hide();
  }
  
  
  private buildFilters() {
    this.filters = this.fb.group({
      status: this.fb.control('all'),
      keyword: this.fb.control('')
    });
    this.subscriptions.push(this.filters.get('status').valueChanges.subscribe(value => {
      this.onStatusChange(value);
    }));
    this.subscriptions.push(this.filters.get('keyword').valueChanges.subscribe(value => {
      this.onKeywordChange(value);
    }));
  }
  
  onStatusChange(value) {
    this.displayDefaultStakeholders = this.filterStatus(this.defaultStakeholders, value);
    this.displayStakeholders = this.filterStatus(this.stakeholders, value);
  }
  
  onKeywordChange(value) {
    this.displayDefaultStakeholders = this.filterByKeyword(this.defaultStakeholders, value);
    this.displayStakeholders = this.filterByKeyword(this.stakeholders, value);
  }
  
  private filterStatus(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (value === 'all') {
      return stakeholders;
    } else {
      return stakeholders.filter(stakeholder => stakeholder.visibility == value);
    }
  }
  
  private filterByKeyword(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (value === null || 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())
      );
    }
  }
  
  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) => {
        if (stakeholder.defaultId == null) {
          this.defaultStakeholders[this.index] = stakeholder;
        } else {
          this.stakeholders[this.index] = stakeholder;
        }
      };
      this.editStakeholderModal.okButtonText = 'Save Changes';
    } else {
      this.callback = (stakeholder: Stakeholder) => {
        if (stakeholder.defaultId === null) {
          this.defaultStakeholders.push(stakeholder);
        } else {
          this.stakeholders.push(stakeholder);
        }
      };
      this.editStakeholderModal.okButtonText = 'Create';
    }
    this.editStakeholderModal.cancelButtonText = 'Cancel';
    this.editStakeholderModal.okButtonLeft = false;
    this.editStakeholderModal.alertMessage = false;
    this.editStakeholderModal.open();
  }
  
  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.message = 'This stakeholder will permanently be deleted. Are you sure you want to proceed?';
    this.deleteStakeholderModal.open();
  }
  
  public deleteStakeholder() {
    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);
      }
    }, error => {
      UIkit.notification('An error has occurred. Please try again later', {
        status: 'danger',
        timeout: 6000,
        pos: 'bottom-right'
      });
    }));
  }
  
  changeStakeholderStatus(stakeholder: Stakeholder, visibility: Visibility) {
    let path = [
      stakeholder._id
    ];
    this.subscriptions.push(this.stakeholderService.changeVisibility(this.properties.monitorServiceAPIURL, path, visibility).subscribe(visibility => {
      stakeholder.visibility = 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);
  }
  
  private isTab(tab: Tab): boolean {
    switch (tab) {
      case "all":
        return true;
      case "profiles":
        return true;
      case "templates":
        return true;
      default:
        return false;
    }
  }
}
