package main

import (
	"code.justin.tv/dta/necronomicon-user-api/app"
	"database/sql"
	"github.com/goadesign/goa"
)

// EnvironmentController implements the environment resource.
type EnvironmentController struct {
	*goa.Controller
	resources *Resources
}

// NewEnvironmentController creates a environment controller.
func NewEnvironmentController(service *goa.Service) *EnvironmentController {
	return &EnvironmentController{
		Controller: service.NewController("EnvironmentController"),
	}
}

// List runs the list action.
func (c *EnvironmentController) List(ctx *app.ListEnvironmentContext) error {
	resources := c.resources
	db := resources.db
	res := app.EnvironmentMediaCollection{}
	s, err := db.GetSnapshot(ctx.SnapshotID)
	if err == sql.ErrNoRows {
		return ctx.NotFound()
	}
	if err != nil {
		return err
	}
	for envName, configSection := range s.State {
		res = append(res, &app.EnvironmentMedia{
			Name:   envName,
			Parent: configSection.Parent,
			Values: configSection.Values,
		})
	}
	return ctx.OK(res)
}

// Show runs the show action.
func (c *EnvironmentController) Show(ctx *app.ShowEnvironmentContext) error {
	resources := c.resources
	db := resources.db
	snapshot, err := db.GetSnapshot(ctx.SnapshotID)
	if err == sql.ErrNoRows {
		return ctx.NotFound()
	}
	if err != nil {
		return err
	}
	state, err := GetMergedEnvironment(snapshot, ctx.Environment)
	if err != nil {
		return err
	}
	if state == nil {
		return ctx.NotFound()
	}
	res := app.EnvironmentMedia{
		Name:   ctx.Environment,
		Values: state.Values,
	}
	return ctx.OK(&res)
}
