import { Component, Input, ViewChild, OnInit, HostBinding,
    ChangeDetectorRef, ChangeDetectionStrategy } from '@angular/core'
import { ActivatedRoute, ParamMap, Router } from '@angular/router'
import { UntypedFormGroup, FormControl } from '@angular/forms'

import { fadeInAnimation }   from '../../animations'
import {
    ModelDataService,
    Model,
    FieldIntrospection,
} from '../../_services/apollo.service'

@Component({
    selector: 'gisaf-admin-detail',
    templateUrl: './admin-detail.component.html',
    styleUrls: ['./admin-detail.component.css'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    animations: [ fadeInAnimation ]
})

export class AdminDetailComponent implements OnInit {
    /*
    @HostBinding('@fadeInAnimation') fadeInAnimation = true
    @HostBinding('style.display')   display = 'block'
    @HostBinding('style.position')  position = 'absolute'
     */

    @Input() modelName: string
    @Input() pk: string
    model: Model
    item: object
    formGroup: UntypedFormGroup
    fields: FieldIntrospection[]

    constructor(
        protected route: ActivatedRoute,
        protected router: Router,
        public modelDataService: ModelDataService,
        private cdr: ChangeDetectorRef,
    ) {}

    ngOnInit() {
        // Set an empty formGroup
        this.formGroup = new UntypedFormGroup({})
        // In case i'm initiated with the route resolver:
        // TODO: use secondary route
        this.route.data.subscribe(
            (data) => {
                if (Object.keys(data).length != 0) {
                    this.route.params.subscribe(
                        params => {
                            let item = data['item']
                            // FIXME (with secondary route)
                            /*
                            this.setItem(
                                params['modelName'],
                                item['model'],
                                item['item'][params['modelName']][0],
                            )
                            */
                        }
                    )
                }
            }
        )
    }

    setItem(modelName, model, item) {
        // Fill me with the provided model and item data
        // Can be called from the init and route resolver or manually (map, etc)
        this.formGroup = new UntypedFormGroup({})
        this.modelName = modelName
        this.item = item
        this.model = model
        // Get the form fields and build the formGroup controls
        this.fields = this.model.getFormFields(this.formGroup, item)
        this.pk = this.item[this.model.introspection.pkFields()[0].name]
        this.cdr.markForCheck()
    }

    submit() {
        this.modelDataService.mutate(this.model.introspection, this.formGroup.value).subscribe(
            res => {
                console.log('TODO: submit', res)
            }
        )
    }
}
