import { Location } from '@angular/common';
import { Component, Injectable, OnDestroy } from '@angular/core';
import { Router } from '@angular/router';
import { commonReducers, 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 { IItemLayer, ITemporalItemLayer } from '../../models/item.layer';
import * as mapReducers from '../../reducers/map.reducer';
import { TemporalService } from '../../services/temporal.service';
import { ForItemType } from '../for-item/for-itemtype.decorator';
import { AbstractSelectedItemComponent } from '../selected-item/selected-item.component';

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

  constructor(store: Store<mapReducers.State | commonReducers.State>, public itemService: ItemService, itemTypeService: ItemTypeService, location: Location, router: Router,public temporalService:TemporalService) {
    super(store, itemTypeService,itemService,location,router);
  }
  
  ngOnDestroy(): void {
    if (this.sub) this.sub.unsubscribe();
  }

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

  currentItemLayer():IItemLayer {
    return  (this.itemLayer as ITemporalItemLayer)?.selectedItemLayer
  }

  handleNextTemporal(event:MouseEvent) {
    this.store.dispatch(new mapActions.NextTemporal());
    event.preventDefault();    
  }

  handlePreviousTemporal(event:MouseEvent) {
    this.store.dispatch(new mapActions.PreviousTemporal());
    event.preventDefault();
  }

  selectedItem():IItem {
    const temporalItemLayer = this.itemLayer as ITemporalItemLayer;
    if(temporalItemLayer && temporalItemLayer.selectedItemLayer) {
       return temporalItemLayer.selectedItemLayer.item;
    }
    return null;
  }  

  layer(layers:any,layerIndex:number) {
    return layers.find(l => l.index == layerIndex);
  }

  handleGoToChart(item: IItem) {  
    this.router.navigate(['/viewer', 'temporal', 'item', item.parentCode, new Date(Date.parse(item.dataDate)).getUTCFullYear()]);
    return false;
  }
  
  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;       
    })
  }
}
