import {ChangeDetectorRef, Component, EventEmitter, Input, Output} from '@angular/core';
import {UntypedFormBuilder} from "@angular/forms";
import {Filter} from "./searchHelperClasses.class";
import {EnvProperties} from "../../utils/properties/env-properties";
import {ConfigurationService} from "../../utils/configuration/configuration.service";
import {Subscription} from "rxjs";
import {ActivatedRoute, Router} from "@angular/router";
import {properties} from "../../../../environments/environment";

@Component({
  selector: 'quick-selections',
  template: `
    <div *ngIf="!vertical && (resultTypes || quickFilter)">
      <div  *ngIf="quickFilter" class="uk-margin-bottom">
        <mat-slide-toggle name="qf" [(ngModel)]="quickFilter.selected" (ngModelChange)="quickFilterChanged()">
          <span class="uk-text-bold">{{quickFilter.value}}</span>
        </mat-slide-toggle>
      </div>
      <div class="uk-flex uk-flex-middle uk-text-small uk-text-nowrap">
        <div class="uk-width-auto@s uk-width-1-3 uk-flex uk-flex-right uk-text-meta uk-margin-small-right">Include:</div>
        <div class="uk-width-expand">
          <div class="uk-grid uk-grid-small uk-flex-middle uk-child-width-auto@m uk-child-width-1-2@s uk-child-width-1-1" uk-grid>
            <ng-container *ngFor="let value of resultTypes.values">
              <div>
                <input #input type="checkbox" class="uk-checkbox" [(ngModel)]="value.selected" (ngModelChange)="changed()"/>
                <label class="uk-margin-small-left" (click)="input.click()">{{value.name}}</label>
              </div>
            </ng-container>
          </div>
        </div>
      </div>
    </div>

    <div *ngIf="vertical && (resultTypes || quickFilter)" [class.uk-disabled]="isDisabled">
      <search-filter [isDisabled]="isDisabled" [filter]="resultTypes" [showResultCount]='false'
                     (onFilterChange)="changed()" [actionRoute]="actionRoute"></search-filter>
    </div>
  `
})
export class QuickSelectionsComponent {
  @Input() vertical: boolean=false;
  @Input() resultTypes:Filter;
  @Output() typeChange = new EventEmitter();
  @Input() isDisabled;
  @Input() quickFilter: { filter: Filter, selected: boolean, filterId: string, value: string };
  @Input() actionRoute:boolean = false;
  initialized = false;
  properties: EnvProperties = properties;
  showPublications:boolean= false;
  showDatasets:boolean= false;
  showSoftware: boolean = false;
  showOrp: boolean = false;
  showEntities = false;
  queryParams = {};

  subs: Subscription[] = [];

  constructor(private _fb: UntypedFormBuilder, private config: ConfigurationService, private _router: Router, private route: ActivatedRoute, private cdr:ChangeDetectorRef) {
  }

  changed() {

    this.typeChange.emit({});
  }

  quickFilterChanged() {
    if(this.quickFilter.filter) {
      this.quickFilter.filter.countSelectedValues = 0;
      if (this.quickFilter.selected) {
        for (let filterValue of this.quickFilter.filter.values) {
          if((filterValue.name == this.quickFilter.value)) {
            filterValue.selected = true
            this.quickFilter.filter.countSelectedValues = 1;
          }else{
            filterValue.selected = false;
          }
        }
      } else {
        for (let filterValue of this.quickFilter.filter.values) {
          filterValue.selected = false;
        }
      }
    }
    this.typeChange.emit({});
  }

  ngOnInit() {
    this.subs.push(this.route.queryParams.subscribe(params => {
      this.queryParams = Object.assign({}, params);
      this.initializeFilters();
    }));
   //Allow all types
   /* if(this.properties && !this.initialized) {
      if(this.properties.adminToolsCommunity !== "monitor") {
         this.subs.push(this.config.portalAsObservable.subscribe(data => {
          if(data) {
            var showEntity = {};
            for (var i = 0; i < data['entities'].length; i++) {
              showEntity["" + data['entities'][i]["pid"] + ""] = data['entities'][i]["isEnabled"];
            }
            this.showPublications = showEntity["publication"];
            this.showDatasets = showEntity["dataset"];
            this.showSoftware = showEntity["software"];
            this.showOrp = showEntity["orp"];
            this.showEntities = this.showPublications || this.showDatasets || this.showSoftware || this.showOrp;
            this.initialized = true;
            this.initializeFilters();
          }
        }, error => {
          this.showPublications = true;
          this.showDatasets = true;
          this.showSoftware = true;
          this.showOrp = true;
          this.showEntities = true;
          this.initializeFilters();
        }));
      } else {*/
        this.showPublications = true;
        this.showDatasets = true;
        this.showSoftware = true;
        this.showOrp = true;
        this.showEntities = true;
        this.initialized = true;
        this.initializeFilters();
      /*}

    }else{
      this.initializeFilters();
     }*/

  }
  initializeFilters(){
    if(this.showEntities ){
      let selected = [];
      for(let value of this.resultTypes.values){
        if(value.selected){
          selected.push(value.id);
        }
      }
      this.resultTypes.countSelectedValues = selected.length;
    }
    this.typeChange.emit("filters_update");
  }
  public ngOnDestroy() {
    for (let sub of this.subs) {
      sub.unsubscribe();
    }
  }
}
