package auth

import (
	"html/template"
	"io"
	"log"
	"time"

	"code.secondbit.org/uuid"
)

// Context wraps the different storage interfaces and should
// be used as the main point of interaction for the data storage
// layer.
type Context struct {
	template *template.Template
	clients  clientStore
	grants   grantStore
	profiles profileStore
	tokens   tokenStore
}

// Render uses the HTML templates associated with the Context to render the
// template specified by name to out using data to fill any template variables.
func (c Context) Render(out io.Writer, name string, data interface{}) {
	if c.template == nil {
		log.Println("No template set on Context, can't render anything!")
		return
	}
	err := c.template.ExecuteTemplate(out, name, data)
	if err != nil {
		log.Println("Error executing template", name, ":", err)
	}
}

// GetClient returns a single Client by its ID from the
// clientStore associated with the Context.
func (c Context) GetClient(id uuid.ID) (Client, error) {
	if c.clients == nil {
		return Client{}, ErrNoClientStore
	}
	return c.clients.getClient(id)
}

// SaveClient stores the passed Client in the clientStore
// associated with the Context.
func (c Context) SaveClient(client Client) error {
	if c.clients == nil {
		return ErrNoClientStore
	}
	return c.clients.saveClient(client)
}

// UpdateClient applies the specified ClientChange to the Client
// with the specified ID in the clientStore associated with the
// Context.
func (c Context) UpdateClient(id uuid.ID, change ClientChange) error {
	if c.clients == nil {
		return ErrNoClientStore
	}
	return c.clients.updateClient(id, change)
}

// DeleteClient removes the client with the specified ID from the
// clientStore associated with the Context.
func (c Context) DeleteClient(id uuid.ID) error {
	if c.clients == nil {
		return ErrNoClientStore
	}
	return c.clients.deleteClient(id)
}

// ListClientsByOwner returns a slice of up to num Clients, starting at offset (inclusive)
// that have the specified OwnerID in the clientStore associated with the Context.
func (c Context) ListClientsByOwner(ownerID uuid.ID, num, offset int) ([]Client, error) {
	if c.clients == nil {
		return []Client{}, ErrNoClientStore
	}
	return c.clients.listClientsByOwner(ownerID, num, offset)
}

// AddEndpoint stores the specified Endpoint in the clientStore associated with the Context,
// and associates the newly-stored Endpoint with the Client specified by the passed ID.
func (c Context) AddEndpoint(client uuid.ID, endpoint Endpoint) error {
	if c.clients == nil {
		return ErrNoClientStore
	}
	return c.clients.addEndpoint(client, endpoint)
}

// RemoveEndpoint deletes the Endpoint with the specified ID from the clientStore associated
// with the Context, and disassociates the Endpoint from the specified Client.
func (c Context) RemoveEndpoint(client, endpoint uuid.ID) error {
	if c.clients == nil {
		return ErrNoClientStore
	}
	return c.clients.removeEndpoint(client, endpoint)
}

// CheckEndpoint finds Endpoints in the clientStore associated with the Context that belong
// to the Client specified by the passed ID and match the URI passed. If strict is true, only
// exact matches for the URI will be returned. If it is false, matches are performed according
// to RFC 3986 Section 6.
func (c Context) CheckEndpoint(client uuid.ID, URI string, strict bool) (bool, error) {
	if c.clients == nil {
		return false, ErrNoClientStore
	}
	return c.clients.checkEndpoint(client, URI, strict)
}

// ListEndpoints finds Endpoints in the clientStore associated with the Context that belong
// to the Client specified by the passed ID. It returns up to num endpoints, starting at offset,
// exclusive.
func (c Context) ListEndpoints(client uuid.ID, num, offset int) ([]Endpoint, error) {
	if c.clients == nil {
		return []Endpoint{}, ErrNoClientStore
	}
	return c.clients.listEndpoints(client, num, offset)
}

// CountEndpoints returns the number of Endpoints the are associated with the Client specified by the
// passed ID in the clientStore associated with the Context.
func (c Context) CountEndpoints(client uuid.ID) (int64, error) {
	if c.clients == nil {
		return 0, ErrNoClientStore
	}
	return c.clients.countEndpoints(client)
}

// GetGrant returns the Grant specified by the provided code from the grantStore associated with the
// Context.
func (c Context) GetGrant(code string) (Grant, error) {
	if c.grants == nil {
		return Grant{}, ErrNoGrantStore
	}
	return c.grants.getGrant(code)
}

// SaveGrant stores the passed Grant in the grantStore associated with the Context.
func (c Context) SaveGrant(grant Grant) error {
	if c.grants == nil {
		return ErrNoGrantStore
	}
	return c.grants.saveGrant(grant)
}

// DeleteGrant removes the Grant specified by the provided code from the grantStore associated with
// the Context.
func (c Context) DeleteGrant(code string) error {
	if c.grants == nil {
		return ErrNoGrantStore
	}
	return c.grants.deleteGrant(code)
}

// GetProfileByID returns the Profile specified by the provided ID from the profileStore associated with
// the Context.
func (c Context) GetProfileByID(id uuid.ID) (Profile, error) {
	if c.profiles == nil {
		return Profile{}, ErrNoProfileStore
	}
	return c.profiles.getProfileByID(id)
}

// GetProfileByLogin returns the Profile associated with the specified Login from the profileStore associated
// with the Context.
func (c Context) GetProfileByLogin(loginType, value string) (Profile, error) {
	if c.profiles == nil {
		return Profile{}, ErrNoProfileStore
	}
	return c.profiles.getProfileByLogin(loginType, value)
}

// SaveProfile inserts the passed Profile into the profileStore associated with the Context.
func (c Context) SaveProfile(profile Profile) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.saveProfile(profile)
}

// UpdateProfile applies the supplied ProfileChange to the Profile that matches the specified ID
// in the profileStore associated with the Context.
func (c Context) UpdateProfile(id uuid.ID, change ProfileChange) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.updateProfile(id, change)
}

// UpdateProfiles applies the supplied BulkProfileChange to every Profile that matches one of the
// specified IDs in the profileStore associated with the Context.
func (c Context) UpdateProfiles(ids []uuid.ID, change BulkProfileChange) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.updateProfiles(ids, change)
}

// DeleteProfile removes the Profile specified by the passed ID from the profileStore associated
// with the Context.
func (c Context) DeleteProfile(id uuid.ID) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.deleteProfile(id)
}

// AddLogin stores the passed Login in the profileStore associated with the Context. It also associates
// the newly-created Login with the Orofile in login.ProfileID.
func (c Context) AddLogin(login Login) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.addLogin(login)
}

// RemoveLogin removes the specified Login from the profileStore associated with the Context, provided
// the Login has a ProfileID property that matches the profile ID passed in. It also disassociates the
// deleted Login from the Profile in login.ProfileID.
func (c Context) RemoveLogin(loginType, value string, profile uuid.ID) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.removeLogin(loginType, value, profile)
}

// RecordLoginUse sets the LastUsed property of the Login specified in the profileStore associated with
// the Context to the value passed in as when.
func (c Context) RecordLoginUse(loginType, value string, when time.Time) error {
	if c.profiles == nil {
		return ErrNoProfileStore
	}
	return c.profiles.recordLoginUse(loginType, value, when)
}

// ListLogins returns a slice of up to num Logins associated with the specified Profile from the profileStore
// associated with the Context, skipping offset Profiles.
func (c Context) ListLogins(profile uuid.ID, num, offset int) ([]Login, error) {
	if c.profiles == nil {
		return []Login{}, ErrNoProfileStore
	}
	return c.profiles.listLogins(profile, num, offset)
}

// GetToken returns the Token specified from the tokenStore associated with the Context.
// If refresh is true, the token input should be compared against the refresh tokens, not the
// access tokens.
func (c Context) GetToken(token string, refresh bool) (Token, error) {
	if c.tokens == nil {
		return Token{}, ErrNoTokenStore
	}
	return c.tokens.getToken(token, refresh)
}

// SaveToken stores the passed Token in the tokenStore associated with the Context.
func (c Context) SaveToken(token Token) error {
	if c.tokens == nil {
		return ErrNoTokenStore
	}
	return c.tokens.saveToken(token)
}

// RemoveToken removes the Token identified by the passed token string from the tokenStore associated
// with the Context.
func (c Context) RemoveToken(token string) error {
	if c.tokens == nil {
		return ErrNoTokenStore
	}
	return c.tokens.removeToken(token)
}

// GetTokensByProfileID returns a slice of up to num Tokens with a ProfileID that matches the specified
// profileID from the tokenStore associated with the Context, skipping offset Tokens.
func (c Context) GetTokensByProfileID(profileID uuid.ID, num, offset int) ([]Token, error) {
	if c.tokens == nil {
		return []Token{}, ErrNoTokenStore
	}
	return c.tokens.getTokensByProfileID(profileID, num, offset)
}
