import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core'
import { ActivatedRoute, Router } from '@angular/router'
import { combineLatest } from 'rxjs'

import { MapControlService } from '../map-control.service'
import { MatOptionSelectionChange } from '@angular/material/core'

import { MapDataService } from '../map-data.service'
import { UntypedFormGroup, UntypedFormControl } from '@angular/forms'
import { BaseMapWithStores } from '../../openapi'

@Component({
    selector: 'gisaf-map-base-map',
    templateUrl: './base-map.component.html',
    styleUrls: ['./base-map.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BaseMapComponent implements OnInit {
    constructor(
        protected mapControlService: MapControlService,
        public mapDataService: MapDataService,
        protected route: ActivatedRoute,
        protected router: Router,
        private cdr: ChangeDetectorRef,
    ) {}

    formGroup: UntypedFormGroup

    ngOnInit() {
        this.route.paramMap.subscribe(
            (params) => {
                let baseMapParams = params.get('baseMap')
                if (baseMapParams) {
                    let baseMapNameList = baseMapParams ? baseMapParams.split(',') : []
                    baseMapNameList.forEach(
                        baseMapName => {
                            let baseMap = this._getBaseMapByName(baseMapName)
                            this.mapControlService.addBaseMapLayers(baseMap.stores)
                        }
                    )
                }
            }
        )

        this.mapControlService.addBaseMap$.subscribe(
            (baseMap: BaseMapWithStores) => {
                let existingIndex = this.mapDataService.mapInitData.baseMaps.findIndex(bm => bm.name == baseMap.name)
                if (existingIndex > -1) {
                    this.mapDataService.mapInitData.baseMaps.splice(existingIndex, 1)
                }
                if (baseMap.stores.length > 0) {
                    this.mapDataService.mapInitData.baseMaps.push(baseMap)
                    this.formGroup.controls['baseMaps'].setValue([baseMap.name])
                }
                this.cdr.markForCheck()
            }
        )

        this.formGroup = new UntypedFormGroup({})
        this.formGroup.addControl('baseMaps', new UntypedFormControl())
    }

    protected _getBaseMapByName(name: string): BaseMapWithStores {
        return this.mapDataService.mapInitData.baseMaps.find(bm => bm.name == name)
    }

    selChange(evt: MatOptionSelectionChange, baseMap: BaseMapWithStores) {
        if (evt.isUserInput) {
            if (evt.source.selected) {
                this.mapControlService.addBaseMapLayers(baseMap.stores)
            }
            else {
                this.mapControlService.removeBaseMapLayers(baseMap.stores)
            }
            this.mapControlService.updateSelection.next(true)
        }
    }
}