import {Component} from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {PluginOpenAIREProducts} from "./plugin-openaire-products.component";
import {PluginBaseFormComponent, PluginEditEvent} from "../../utils/base-plugin.form.component";

@Component({
  selector: 'plugin-openaire-products-form',
  template: `
    <div *ngIf="pluginObject" class="uk-padding-xsmall">
          <plugin-field-edit [value]="pluginObject.title" 
                             type="text" field="title"   (changed)="valueChanged($event)" ></plugin-field-edit>
      
      <div class="uk-margin-medium-top uk-text-muted">
        Select services:
      </div>
        <ng-container *ngFor="let service of services">
          
            <div class="  uk-margin-xsmall-top">
              <plugin-field-edit [value]="pluginObject.serviceIdsArray.indexOf(service.id)!=-1"
                                 type="checkbox" field="sdgs" (editClicked)="pluginEditEvent = $event"
                                 (changed)="serviceChanged(service.id,$event)">
              </plugin-field-edit>
                  {{service.name}} 
            </div>
        </ng-container>
      <div *ngIf="showErrorMessage"  class="uk-text-muted uk-text-center">
        No products info available

      </div>

    </div>
  
  `,


})
//TODO make it extend PluginOpenaireProductsComponent (to avoid call in constructor..)
export class PluginOpenaireProductsFormComponent extends PluginBaseFormComponent<PluginOpenAIREProducts>{
  default = new PluginOpenAIREProducts();
  services = [];
  excludedServiceIds = ["openaire_login","research_community_dashboard"]
  api= "https://catalogue.openaire.eu/api/catalogue-resources?from=0&quantity=100&order=asc&orderField=name";
  showErrorMessage = false;
  constructor(http:HttpClient) {
    super()
    this.subscriptions.push(http.get( this.properties.cacheUrl + encodeURIComponent(this.api)).subscribe(res =>{
      this.services = res["results"].map( x=> {
        x.id = x.id.split("openaire.")[1]
        return x;
      });
      this.services = this.services.filter(x=> this.excludedServiceIds.indexOf(x.id) ==-1);
    }, error => {
      this.showErrorMessage = true;
    }))

  }

  serviceChanged(id,$event:PluginEditEvent){
      let index = this.pluginObject.serviceIdsArray.indexOf(id);
      if(index !=-1){
        this.pluginObject.serviceIdsArray.splice(index,1);
      }else{
        this.pluginObject.serviceIdsArray.push(id);
      }
      $event.value =this.pluginObject.serviceIdsArray;

    this.valuesChanged.emit({field:$event.field, value: $event.value, type: 'parent'})
  }

}
