import { Component, OnInit, ViewChild, ElementRef } from '@angular/core'
import { UntypedFormControl } from '@angular/forms'
import { ActivatedRoute, Router, ParamMap } from '@angular/router'

import { Observable, of } from 'rxjs'
import { map, startWith, switchMap } from 'rxjs/operators'

import { DataService } from '../../_services/data.service'
import { ConfigService } from '../../_services/config.service'
import { MeasuresItem, DataProvider } from '../../openapi'

@Component({
    selector: 'gisaf-measures-list',
    templateUrl: './measures-list.component.html',
    styleUrls: ['./measures-list.component.scss'],
})
export class MeasuresListComponent implements OnInit {
    @ViewChild('ipt', { static: true }) ipt: ElementRef
    //routerItems: Object[] = []
    measuresItems: MeasuresItem[] = []

    id: string
    store: string  // = conf['measures']['defaultStore']

    filteredOptions: Observable<MeasuresItem[]>
    myControl: UntypedFormControl = new UntypedFormControl()

    constructor(
        public configService: ConfigService,
        private dataService: DataService,
        private route: ActivatedRoute,
        private router: Router,
    ) {}

    ngOnInit() {
        this.route.paramMap.pipe(
            switchMap(
                (params: ParamMap) => {
                    let store = params.get('store')
                    if (store) {
                        this.store = store
                        return this.dataService.getList(store)
                    }
                    else {
                        this.router.navigate(['/measures', this.configService.conf['measures']['defaultStore']])
                        return of([])
                    }
                }
            )
        ).subscribe({
            next: measuresItems => {
                this.measuresItems = measuresItems
                // Refresh the dropdown
                this.myControl.reset()
            },
            error: err => {
                console.log(err)
            }
        })

        this.filteredOptions = this.myControl.valueChanges.pipe(
            startWith(''),
            //map(val => this.filter(val)),
            map(
                measuresItem => {
                    if (measuresItem) {
                        if (typeof measuresItem === 'object') {
                            this.navigate(measuresItem['id'])
                            return measuresItem['name']
                        }
                        return measuresItem
                    }
                }
            ),
            map(
                name => {
                    if (!name || this.measuresItems.filter(ri => ri.name === name).length) {
                        return this.measuresItems.slice()
                    }
                    if (typeof name === 'string') {
                        return this.filter(name)
                    }
                }
            )
        )
    }
                //this.id = params['id']

/*
                this.dataService.getList(this.store).subscribe(
                    data => {
                        this.routerItems = data.map(item => {
                            let id = item['$uri'].substr(item['$uri'].lastIndexOf('/') + 1)
                            return { name: item['caption'] || id, id: id }
                        })
                        if (this.id) {
                            let name_list = this.routerItems.filter(i => i['id'] === this.id)
                            if (name_list.length === 1) {
                                var name: any = name_list[0]
                            }
                            else {
                                var name: any = { name: '' }
                            }
                            //let name = name_list.length === 1 : name_list[0]['name'] ? ''
                            this.myControl.setValue(name)
                        }
                        this.filteredOptions = this.myControl.valueChanges.pipe(
                            startWith(''),
                            //map(val => this.filter(val)),
                            map(
                                typeId => {
                                    if (typeId) {
                                        if (typeof typeId === 'object') {
                                            this.navigate(typeId['id'])
                                            return typeId['name']
                                        }
                                        return typeId
                                    }
                                }
                            ),
                            map(
                                name => {
                                    if (!name || this.routerItems.filter(ri => ri['name'] === name).length) {
                                        return this.routerItems.slice()
                                    }
                                    if (typeof name === 'string') {
                                        return this.filter(name)
                                    }
                                }
                            )
                        )
                    }
                )
                */

    filter(val: string): MeasuresItem[] {
        let filter = val.toLowerCase()
        return this.measuresItems.filter(option => {
            return option.name.toLowerCase().indexOf(filter) != -1
        })
    }

    displayFn(item: any): string {
        return item ? item.name : item
    }

    navigate(selectedId): void {
        // Hack for nagivating with this class from a subclass, where
        // the route is store/id
        this.router.navigate(
            [
                '/measures', this.store, selectedId
                //'/measures/' + this.store,
                /*
                {
                    outlets: {
                        info: [
                            this.store,
                            +selectedId,
                        ]
                    }
                }
                */
            ],
        ).then(_ => {
            this.ipt.nativeElement.blur()
        })
        /*
        if (this.route.url['value'].length === 2) {
            this.router.navigate(['../' + selectedId], { relativeTo: this.route })

        }
        else {
            this.router.navigate([selectedId], { relativeTo: this.route })
        }
        */
    }
}
