import { Component, Input, OnDestroy} from '@angular/core';
import { IItemLinkType} from '../../models/itemlink.type'
import { IUrlType } from '../../models/url.type';
import { ItemService } from '../../common-service.module';
import { Subscription } from 'rxjs';
import { ClipboardService } from 'ngx-clipboard'


@Component({
    selector: 'fm-item-link',
    templateUrl: './item-link.component.html',
    standalone: false
})
export class ItemLinkComponent implements OnDestroy {

  @Input() itemCode:string;
  @Input() pathSuffix:string;
  @Input() query:string;
  @Input() validMinutes:number;
  @Input() showText:boolean;

  private sub : Subscription = null;

  constructor(private itemService:ItemService,private clipboardService$: ClipboardService) { }

  copylink(tooltip) {
    if(this.sub)  {
        this.sub.unsubscribe();
    }
    let link: IItemLinkType = {itemcode:this.itemCode,pathsuffix:this.pathSuffix,query:this.query,validminutes:this.validMinutes}
    this.sub = this.itemService.getItemLink(link).subscribe((url:IUrlType) => { 
        this.clipboardService$.copy(url.url);
        tooltip.open();
        setTimeout(() => {
            tooltip.close();
        }, 2000);
    })
  }

  ngOnDestroy(): void {
    if(this.sub) {
        this.sub.unsubscribe();
    }      
  }
}
