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} 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/dashboard/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 "../manageStakeholder/edit-stakeholder/edit-stakeholder.component";

declare var UIkit;

@Component({
  selector: 'home',
  templateUrl: "./manageStakeholders.component.html"
})
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 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
   */
  public grid: boolean = true;
  private subscriptions: any[] = [];
  @ViewChild('editStakeholderModal') editStakeholderModal: AlertModal;
  @ViewChild('deleteStakeholderModal') deleteStakeholderModal: AlertModal;
  @ViewChild('editStakeholderComponent') editStakeholderComponent: EditStakeholderComponent;
  
  constructor(private stakeholderService: StakeholderService,
              private userManagementService: UserManagementService,
              private propertiesService: EnvironmentSpecificService,
              private title: Title,
              private fb: FormBuilder) {
  }
  
  ngOnInit(): void {
    this.buildFilters();
    this.propertiesService.loadEnvironment()
      .then(properties => {
        this.properties = properties;
        this.title.setTitle('Manage profiles');
        this.userManagementService.getUserInfo().subscribe(user => {
          this.user = user;
        });
        let data = zip(
          this.stakeholderService.getDefaultStakeholders(this.properties.monitorServiceAPIURL),
          this.stakeholderService.getStakeholders(this.properties.monitorServiceAPIURL)
        );
        data.subscribe(res => {
          this.defaultStakeholders = res[0];
          this.stakeholders = res[1];
          this.displayDefaultStakeholders = res[0];
          this.displayStakeholders = res[1];
          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();
  }
  
  public changeGrid(value) {
    this.grid = value;
  }
  
  private buildFilters() {
    this.filters = this.fb.group({
      privacy: this.fb.control('all'),
      status: this.fb.control('all'),
      keyword: this.fb.control('')
    });
    this.subscriptions.push(this.filters.get('privacy').valueChanges.subscribe(value => {
      this.onPrivacyChange(value);
    }));
    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);
    }));
  }
  
  onPrivacyChange(value) {
    this.displayDefaultStakeholders = this.filterPrivacy(this.defaultStakeholders, value);
    this.displayStakeholders = this.filterPrivacy(this.stakeholders, 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 filterPrivacy(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (value === 'all') {
      return stakeholders;
    } else {
      return stakeholders.filter(stakeholder => stakeholder.isPublic === value);
    }
  }
  
  private filterStatus(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (value === 'all') {
      return stakeholders;
    } else {
      return stakeholders.filter(stakeholder => stakeholder.isActive === value);
    }
  }
  
  private filterByKeyword(stakeholders: Stakeholder[], value): Stakeholder[] {
    if (value === null || value === '') {
      return stakeholders;
    } else {
      return stakeholders.filter(stakeholder => (
        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.stakeholders, 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.stakeholderService.deleteElement(this.properties.monitorServiceAPIURL, [this.stakeholder._id]).subscribe(() => {
      if (!this.stakeholder.defaultId) {
        this.defaultStakeholders.splice(this.index, 1);
      } else {
        this.stakeholders.splice(this.index, 1);
      }
    });
  }
  
  toggleStakeholderStatus(stakeholder: Stakeholder) {
    let path = [
      stakeholder._id
    ];
    this.stakeholderService.toggleStatus(this.properties.monitorServiceAPIURL, path).subscribe(isActive => {
      stakeholder.isActive = isActive;
    });
  }
  
  toggleStakeholderAccess(stakeholder: Stakeholder) {
    let path = [
      stakeholder._id
    ];
    this.stakeholderService.toggleAccess(this.properties.monitorServiceAPIURL, path).subscribe(isPublic => {
      stakeholder.isPublic = isPublic;
    });
  }
  
  public isAdministrator(): boolean {
    return Session.isPortalAdministrator(this.user);
  }
}
