import {
    api,
    Builder,
    collect,
    Config,
    Controller,
    DatabaseService,
    DataContainer,
    hasOwnProperty,
    HTTPError,
    HTTPStatus,
    Inject,
    Injectable,
    Maybe,
    QueryRow, view,
} from '@extollo/lib'
import {FieldDefinition, FieldType, ResourceAction, ResourceConfiguration} from '../../../cobalt'


@Injectable()
export class Interface extends Controller {
    @Inject()
    protected readonly config!: Config

    public listing(key: string) {
        this.getResourceConfigOrFail(key)
        return view('dash:listing', {
            resourcekey: key
        })
    }

    public updateForm(key: string, id: number|string) {
        this.getResourceConfigOrFail(key)
        return view('dash:form', {
            resourcekey: key,
            resourceid: id,
            resourcemode: 'edit'
        })
    }

    public viewForm(key: string, id: number|string) {
        this.getResourceConfigOrFail(key)
        return view('dash:form', {
            resourcekey: key,
            resourceid: id,
            resourcemode: 'view',
        })
    }

    public insertForm(key: string) {
        this.getResourceConfigOrFail(key)
        return view('dash:form', {
            resourcekey: key,
            resourcemode: 'insert',
        })
    }

    protected getResourceConfigOrFail(key: string): ResourceConfiguration {
        const config = this.getResourceConfig(key)
        if ( !config ) {
            throw new HTTPError(HTTPStatus.NOT_FOUND)
        }
        return config
    }

    protected getResourceConfig(key: string): Maybe<ResourceConfiguration> {
        const configs = this.config.get('cobalt.resources') as ResourceConfiguration[]
        for ( const config of configs ) {
            if ( config.key === key ) {
                return config
            }
        }
    }
}
