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

import { AuthenticationService } from '../../_services/authentication.service'
import { Node, LayerNode } from '../models'
import { MapControlService } from '../map-control.service'
import { Observable, map, of } from 'rxjs'

@Component({
    selector: 'gisaf-tree-layer-item',
    templateUrl: './tree-layer-item.component.html',
    styleUrls: ['./tree-layer-item.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class TreeLayerItemComponent implements OnInit {
    @Input() node: LayerNode | Node
    @Input() checked: boolean = false
    @Input() layerNodeMenu: any
    @Input() layerGroupNodeMenu: any
    @Output() layerItemSelectionToggle: EventEmitter<Node> = new EventEmitter<Node>()
    @Output() toggleNode: EventEmitter<Event> = new EventEmitter<Event>()
    indeterminate = false

    constructor(
        protected mapControlService: MapControlService,
        private cdr: ChangeDetectorRef,
        public authenticationService: AuthenticationService,
    ) {}

    ngOnInit() {
        this.node.treeElement = this
        if (this.checked) {
            //this.showLayer.emit(this)
            // XXX: is it right?
            this.mapControlService.addLayer(<LayerNode>this.node)
        }
    }

    isHidden(): Observable<boolean> {
        let role: string = (<LayerNode>this.node).viewableRole
        if (!role) {
            return of(false)
        }
        else {
            return this.authenticationService.isNotAuthorized([role])
        }
    }

    toggleLayer(event): void {
        this.layerItemSelectionToggle.emit(this.node)
        if (this.node instanceof LayerNode) {
            this.mapControlService.updateSelection.next(true)
            if (event.checked) {
                this.indeterminate = true
                this.mapControlService.addLayer(<LayerNode>this.node)
            }
            else {
                this.mapControlService.removeLayer(this.node)
            }
        }
    }
}
