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

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

import { map, switchMap } from 'rxjs/operators'

// import { gql } from 'apollo-angular'

import { ModelDataService, JoinField } from '../../_services/apollo.service'
import { Relation } from '../models'

@Component({
    selector: 'join-select',
    templateUrl: './join-select.component.html',
    changeDetection: ChangeDetectionStrategy.OnPush,
})
export class JoinSelectComponent implements OnInit {
    @Input() join: JoinField
    @Input() formGroup: UntypedFormGroup
    choices: object[]

    constructor(
        protected modelDataService: ModelDataService,
        private cdr: ChangeDetectorRef,
    ) {}

    ngOnInit() {
        var modelName = this.join.target.split('.').pop()
        console.warn('Migrate Graphql')
        let query = ''
        // let query = gql`query model {${modelName}{name id}}`
        this.modelDataService.get(query).pipe(map(data => {
            return data[modelName]
        })).subscribe(data => {
            this.choices = data.map(
                item => {
                    return {id: +item['id'], name: item['name']}
                }
            )
            this.cdr.markForCheck()
        })
    }
}
