import { Location } from '@angular/common';
import { Component, Injectable, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { commonReducers, FolderService, IItem, IItemLinkType, ItemService, ItemTypeService, IUrlType } from '@farmmaps/common';
import { Store } from '@ngrx/store';
import { Subscription } from 'rxjs';
import * as mapActions from '../../actions/map.actions';
import * as mapReducers from '../../reducers/map.reducer';
import { ForItemType } from '../for-item/for-itemtype.decorator';
import { AbstractSelectedItemComponent } from '../selected-item/selected-item.component';


@ForItemType("vnd.farmmaps.itemtype.geotiff.processed")
@Injectable()
@Component({
  selector: 'fm-map-selected-item-geotiff',
  templateUrl: './selected-item-geotiff.component.html',
  styleUrls: ['./selected-item-geotiff.component.scss']
})
export class SelectedItemGeotiffComponent extends AbstractSelectedItemComponent implements OnDestroy {
  sub: Subscription;

  constructor(store: Store<mapReducers.State | commonReducers.State>, public itemService: ItemService, itemTypeService: ItemTypeService, location: Location, router: Router, private itemService$: ItemService,private folderService$: FolderService) {
    super(store, itemTypeService,itemService,location,router);
  }

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

  onLayerChanged(layerIndex: number) {
    this.store.dispatch(new mapActions.SetLayerIndex(layerIndex));
  }

  layer(layers:any,layerIndex:number) {
    return layers.find(l => l.index == layerIndex);
  }
  
  download(event:MouseEvent,item:IItem,layers:any,layerIndex:number) {
    event.stopPropagation();
    event.preventDefault();
    const itemLink : IItemLinkType = {itemcode:item.code,query:`layer=${this.layer(layers,layerIndex).name}`,pathsuffix:"download", validminutes:10}
    this.sub = this.itemService.getItemLink(itemLink).subscribe((itemLinkUrl:IUrlType) => {  
        window.location.href = itemLinkUrl.url;     
    })
  }
}
