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

import { UntypedFormGroup, UntypedFormControl } from '@angular/forms'

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

import { AdminManageDataService, RawSurveyPoint } from '../data.service'
import { CategoryRead } from '../../../openapi'

@Component({
    selector: 'gisaf-admin-points-by-orig-id',
    templateUrl: './points-by-orig-id.component.html',
    styleUrls: ['./points-by-orig-id.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AdminPointsByOrigIdComponent implements OnInit {
    formGroup: UntypedFormGroup
    categories: CategoryRead[]
    rawSurveyPoints: RawSurveyPoint[]
    filteredCategories: Observable<CategoryRead[]>
    destinationControl: UntypedFormControl = new UntypedFormControl()

    constructor(
        private adminManageDataService: AdminManageDataService,
        private cdr: ChangeDetectorRef,
    ) {}

    ngOnInit() {
        this.formGroup = new UntypedFormGroup({})
        this.formGroup.addControl('originalId', new UntypedFormControl())
        this.formGroup.addControl('newStatus', new UntypedFormControl())
        this.formGroup.addControl('canDelete', new UntypedFormControl())
        this.formGroup.addControl('destination', this.destinationControl)
        this.adminManageDataService.getCategories().subscribe(
            categories => {
                this.categories = categories
                this.filteredCategories = this.destinationControl.valueChanges.pipe(
                    startWith(''),
                    map(value => this._filter(value))
                )
            }
        )
    }

    private _filter(value: string): CategoryRead[] {
        const filterValue = value.toUpperCase()
        return this.categories.filter(
            category => category.name.indexOf(filterValue) != -1
                || category.group.toUpperCase().indexOf(filterValue) != -1
                || category.minor_group_1.toUpperCase().indexOf(filterValue) != -1
        )
    }

    submit() {
        this.adminManageDataService.getRawSurveyPoints(this.formGroup.value['originalId']).subscribe(
            res => {
                this.rawSurveyPoints = res
                this.cdr.markForCheck()
            }
        )
    }
}
