import {Component, OnDestroy, OnInit, ViewChild} from "@angular/core";
import {StakeholderService} from "../services/stakeholder.service";
import {EnvProperties} from "../openaireLibrary/utils/properties/env-properties";
import {EnvironmentSpecificService} from "../openaireLibrary/utils/properties/environment-specific.service";
import {Stakeholder} from "../utils/entities/stakeholder";
import {Subscriber, zip} from "rxjs";
import {IndicatorUtils, Option, StakeholderUtils} from "../utils/indicator-utils";
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {AlertModal} from "../openaireLibrary/utils/modal/alert";

@Component({
  selector: 'home',
  templateUrl: "./home.component.html"
})
export class HomeComponent 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 stakeholderFb: FormGroup;
  public index: number;

  /**
   *  Filtered Stakeholders
   */
  public displayDefaultStakeholders: Stakeholder[];
  public displayStakeholders: Stakeholder[];

  /**
   * Top filters
   */
  public filters: FormGroup;
  public all: Option = {
    value: 'all',
    label: 'All'
  };

  /**
   * Grid or List View
   */
  public grid: boolean = true;
  private subscriptions: any[] = [];

  @ViewChild('editStakeholderModal') editStakeholderModal: AlertModal;
  @ViewChild('deleteStakeholderModal') deleteStakeholderModal: AlertModal;

  constructor(private stakeholderService: StakeholderService,
              private propertiesService: EnvironmentSpecificService,
              private fb: FormBuilder) {
  }

  ngOnInit(): void {
    this.buildFilters();
    this.propertiesService.loadEnvironment()
      .then(properties => {
        this.properties = properties;
        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;
        });
      });
  }

  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      }
    });
  }

  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, isDefault, null, false, false);
    } else {
      this.stakeholder = stakeholder;
    }
    this.stakeholderFb = this.fb.group( {
      _id: this.fb.control(stakeholder._id),
      index_name: this.fb.control(stakeholder.index_name, Validators.required),
      index_id: this.fb.control(stakeholder.index_id, Validators.required),
      index_shortName: this.fb.control(stakeholder.index_shortName, Validators.required),
      isDefaultProfile: this.fb.control(stakeholder.isDefaultProfile),
      alias: this.fb.control(stakeholder.alias, Validators.required),
      isPublic: this.fb.control(stakeholder.isPublic),
      isActive: this.fb.control(stakeholder.isActive),
      type: this.fb.control(stakeholder.type, Validators.required),
      topics: this.fb.control(stakeholder.topics)
    });
    if(this.index !== -1) {
      this.stakeholderFb.get('type').disable();
    }
    this.editStakeholderModal.cancelButtonText = 'Cancel';
    this.editStakeholderModal.okButtonText = 'Save Changes';
    this.editStakeholderModal.okButtonLeft = false;
    this.editStakeholderModal.alertMessage = false;
    this.editStakeholderModal.open();
  }

  public saveStakeholder() {

  }

  public deleteStakeholderOpen(stakeholder: Stakeholder, isDefault = 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;
    }
  }

  public deleteStakeholder() {

  }
}
