package server

import (
	"code.justin.tv/creator-collab/log/errors"
	"code.justin.tv/live/autohost/lib"
	"code.justin.tv/live/autohost/rpc/hosting"
	"github.com/twitchtv/twirp"
)

func convertSettings(settings *lib.Settings) (*hosting.AutohostSettings, error) {
	strategy, err := convertStrategy(settings.Strategy)
	if err != nil {
		return nil, err
	}

	return &hosting.AutohostSettings{
		Enabled:             settings.Enabled,
		TeamHost:            settings.TeamHost,
		Strategy:            strategy,
		DeprioritizeVodcast: settings.DeprioritizeVodcast,
	}, nil
}

func convertStrategy(strategy lib.AutohostStrategy) (hosting.AutohostStrategy, error) {
	switch strategy {
	case lib.AutohostStrategyRandom:
		return hosting.AutohostStrategy_AUTOHOST_STRATEGY_RANDOM, nil
	case lib.AutohostStrategyOrdered:
		return hosting.AutohostStrategy_AUTOHOST_STRATEGY_ORDERED, nil
	}

	err := errors.New("could not convert lib.AutohostStrategy to hosting.AutohostStrategy", errors.Fields{
		"strategy": string(strategy),
	})
	return hosting.AutohostStrategy_AUTOHOST_STRATEGY_UNSET, err
}

func convertTwirpStrategy(twirpStrategy hosting.AutohostStrategy) (lib.AutohostStrategy, error) {
	switch twirpStrategy {
	case hosting.AutohostStrategy_AUTOHOST_STRATEGY_RANDOM:
		return lib.AutohostStrategyRandom, nil
	case hosting.AutohostStrategy_AUTOHOST_STRATEGY_ORDERED:
		return lib.AutohostStrategyOrdered, nil
	}

	err := errors.New("could not convert hosting.AutohostStrategy to lib.AutohostStrategy", errors.Fields{
		"twirpStrategy": string(twirpStrategy),
	})
	return "", err
}

func convertUpdateAutohostSettingsRequest(request *hosting.UpdateAutohostSettingsRequest) (*lib.UpdateSettingsInput, error) {
	input := &lib.UpdateSettingsInput{}

	if request.Strategy != hosting.AutohostStrategy_AUTOHOST_STRATEGY_UNSET {
		strategy, err := convertTwirpStrategy(request.Strategy)
		if err != nil {
			return nil, twirp.InvalidArgumentError("Strategy", "Strategy value was not recognized")
		}
		input.Strategy = &strategy
	}

	if request.Enabled != nil {
		enabled := request.Enabled.Value
		input.Enabled = &enabled
	}

	if request.TeamHost != nil {
		teamHost := request.TeamHost.Value
		input.TeamHost = &teamHost
	}

	if request.DeprioritizeVodcast != nil {
		deprioritizeVodcast := request.DeprioritizeVodcast.Value
		input.DeprioritizeVodcast = &deprioritizeVodcast
	}

	return input, nil
}
