import {Component, Input} from '@angular/core';

import { ConeSearch, Resolver } from '../store/model';
import { Observable } from "rxjs";
import { Store } from "@ngrx/store";
import * as coneSearchSelector from "../store/cone-search.selector";
import * as fromConeSearch from "../store/cone-search.reducer";
import * as coneSearchActions from '../store/cone-search.action';

interface StoreState {
    coneSearch: fromConeSearch.State;
}

@Component({
    selector: 'app-cone-search',
    templateUrl: 'cone-search.component.html'
})
export class ConeSearchComponent {
    @Input() disabled: boolean = false;
    public resolverWip: Observable<boolean>;
    public resolver: Observable<Resolver>;
    public coneSearch: Observable<ConeSearch>;

    unit = 'degree';
    ra: number;
    dec: number;
    radius: number;

    constructor(private store: Store<StoreState>) {
        this.resolverWip = store.select(coneSearchSelector.getResolverWip);
        this.resolver = store.select(coneSearchSelector.getResolver);
        this.coneSearch = store.select(coneSearchSelector.getConeSearch);
    }

    retrieveCoordinates(name: string): void {
        this.store.dispatch(new coneSearchActions.RetrieveCoordinatesAction(name));
    }

    csChange(prop: string, value: number): void {
        switch(prop) {
            case 'ra':
                this.ra = +value;
                break;
            case 'dec':
                this.dec = +value;
                break;
            case 'radius':
                this.radius = value;
                break;
        }
        this.isValid();
    }

    isValid(): void {
        console.log(this.ra, this.dec, this.radius);
        if (this.ra && this.dec && this.radius) {
            const cs = { ra: this.ra, dec: this.dec, radius: this.radius} as ConeSearch;
            this.store.dispatch(new coneSearchActions.AddConeSearchAction(cs));
            this.store.dispatch(new coneSearchActions.IsValidConeSearchAction(true));
        } else {
            this.store.dispatch(new coneSearchActions.IsValidConeSearchAction(false));
        }
    }

    deleteResolver(): void {
        this.store.dispatch(new coneSearchActions.DeleteResolverAction());
    }
}