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

import { MatSnackBar } from '@angular/material/snack-bar'

import { FullInfo, InfoDataService } from '../info-data.service'
import { MapControlService } from '../../map/map-control.service'
import { Tag, TagsPluginsService, TagAction } from './tags.service'
import { AuthenticationService } from '../../_services/authentication.service'

@Component({
    selector: 'gisaf-tag',
    templateUrl: './tag.component.html',
    styleUrls: ['./tag.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class TagComponent implements OnInit {
    @Input() source: FullInfo
    /*
    @Input() set source(_source: FullInfo) {
        this._source = _source
        this.cdr.markForCheck()
    }
    */
    @Input() tag: Tag
    actions: TagAction[] = []

    constructor(
        private snackBar: MatSnackBar,
        private tagsPluginsService: TagsPluginsService,
        protected mapControlService: MapControlService,
        protected infoDataService: InfoDataService,
        private authenticationService: AuthenticationService,
        private cdr: ChangeDetectorRef,
    ) {}

    ngOnInit() {
        // Find applicable tag actions
        this.tagsPluginsService.getTagsPlugins().subscribe(
            stores => {
                const fstores = stores.stores.filter(store => store.store == this.source.modelInfo.store)
                for (let store of fstores) {
                    for (let tagAction of store.tagActions) {
                        if (tagAction.fullKey == this.tag.key) {
                            this.actions = tagAction.actions
                            return
                        }
                    }
                }
            }
        )
    }

    get isAuthorized() {
        // At least one role of the user must match the roles of the action
        return this.authenticationService.roles.filter(
            role => this.actions.map(
                action => action.roles.indexOf(role.name) != -1
            )
        ).length > 0
    }

    getUrl(action: TagAction) {
        return action.link.replace('{value}', this.tag.value)
    }

    followLink(action: TagAction) {
        window.open(this.getUrl(action))
    }

    doAction(store: string, id: string, action: TagAction, value: string) {
        this.tagsPluginsService.doAction(store, id, action, value).subscribe(
            resp => {
                this.snackBar.open(resp, 'Close', {duration: 3000})
                // Refresh display
                this.infoDataService.refresh.next(true)
                this.mapControlService.search.next(true)
            }
        )
    }

    delete() {
        this.infoDataService.deleteTag(this.tag, this.source).subscribe({
            next: res => {
                const tags = res['data']['deleteTag']['tags']
                this.source.featureInfo.tags = tags
                this.infoDataService.dataProviderService.next(this.source)
                this.mapControlService.search.next(true)
                this.cdr.markForCheck()
            },
            error: err => {
                console.error(err)
            }
        })
    }
}