import {Component, Input} from '@angular/core';
import {ClaimEntity} from './claimHelper.class';

declare var UIkit: any;

@Component({
  selector: 'claim-results',
  template: `
    <div *ngIf="results.length > 0 " class="uk-margin-top">
      <div *ngFor="let entity of results" class="uk-card">
        <div class="uk-padding-small">
          <div class="uk-grid">
            <div class="uk-width-expand uk-margin-right">
              <claim-title [entity]="entity" [showIcon]="false"></claim-title>
              <claim-result-metadata [entity]="entity"></claim-result-metadata>
              <claim-project-metadata [entity]="entity"></claim-project-metadata>
            </div>
            <div class="uk-margin-auto-vertical uk-padding-remove-left uk-margin-small-left  uk-margin-small-right" [title]="(this.selectedResults.length>=basketLimit)?'Basket reached the size limit':''">
              <button class="linking-add-button uk-icon-button-small" [class.uk-disabled]="(this.selectedResults.length>=basketLimit)" *ngIf="!isSelected(entity)"
                 (click)="add(entity)">
                <icon name="add" [flex]="true"></icon>
              </button>
              <button *ngIf="isSelected(entity)" class="linking-selected-button uk-icon-button-small" (click)="remove(entity)">
                <icon name="check" [flex]="true"></icon>
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  `
})
export class ClaimResultsComponent {
  @Input() results: ClaimEntity[];
  @Input() selectedResults: ClaimEntity[];
  @Input() localStoragePrefix: string = "";
  @Input() basketLimit;

  ngOnInit() {
  }

  public isSelected(item: ClaimEntity) {
    return !!this.selectedResults.find(result => item.id === result.id);
  }

  add(item: ClaimEntity) {
    let found: boolean = this.isSelected(item);
    if (!found) {
      this.selectedResults.push(item);
      localStorage.setItem(this.localStoragePrefix, JSON.stringify(this.selectedResults));
      UIkit.notification(item.type + ' added in your basket!', {
        status: 'success',
        timeout: 4000,
        pos: 'bottom-right'
      });
    }
  }

  remove(item: ClaimEntity) {
    const index: number = this.selectedResults.findIndex(result => item.id === result.id);
    if (index > -1) {
      this.selectedResults.splice(index, 1);
      if (this.selectedResults != null) {
        localStorage.setItem(this.localStoragePrefix, JSON.stringify(this.selectedResults));
      }
      UIkit.notification(item.type + ' removed from your basket!', {
        status: 'warning',
        timeout: 4000,
        pos: 'bottom-right'
      });
    }

  }
}
