import {
  Component, Input,
  ChangeDetectionStrategy, ChangeDetectorRef
} from '@angular/core'

import { Tag } from './tags.service'
import { FullInfo, InfoDataService, FormField } from '../info-data.service'
import { Action, ActionsService } from '../../_services/actions.service'

import { MatSnackBar } from '@angular/material/snack-bar'
import { AuthenticationService } from '../../_services/authentication.service'
import { MapControlService } from '../../map/map-control.service'

@Component({
  selector: 'gisaf-tag-action',
  templateUrl: './tag-action.component.html',
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TagActionComponent {
  @Input() source: FullInfo
  @Input() action: Action
  constructor(
    private actionsService: ActionsService,
    private infoDataService: InfoDataService,
    private snackBar: MatSnackBar,
    public authenticationService: AuthenticationService,
    protected mapControlService: MapControlService,
    private cdr: ChangeDetectorRef,
  ) { }

  execute() {
    this.actionsService.execute(
      [this.source.modelInfo.store],
      [[this.source.featureInfo.id.toString()]],
      [this.action.name],
      this.action.params,
    ).subscribe(
      results => {
        // Update the tags in the info source
        let result = results[0].actionResults[0]
        if (result.message) {
          this.snackBar.open(result.message, 'Close', { duration: 3000 })
        }
        if (!result.actionResults || result.actionResults.length == 0) {
          return
        }
        let layer = result.actionResults[0].taggedLayers.find(
          tl => tl.store == this.source.modelInfo.store
        )
        let feature = layer.features.find(f => f.id == this.source.featureInfo.id)
        if (feature) {
          feature.tags.forEach(
            tag => {
              let existingTag = this.source.featureInfo.tags.find(t => t.key == tag.key)
              if (existingTag) {
                console.log("Tag update: test me!")
                existingTag.value = tag.value
                this.infoDataService.dataProviderService.next(this.source)
              }
              else {
                this.source.featureInfo.tags.push({ key: tag.key, value: tag.value })
              }
            }
          )
          this.infoDataService.dataProviderService.next(this.source)
        }
        // Trick to refresh the tags on the map
        if (this.mapControlService.hasTags.value) {
          this.mapControlService.hasTags.next(true)
        }
      }
    )
  }
}
