package DataSource

import (
	"errors"
	"fmt"
)

type TorrentSelectionMode byte

const (
	TSMODE_ALL             TorrentSelectionMode = 0
	TSMODE_SELECTED        TorrentSelectionMode = 1
	TSMODE_RECENTLY_ACTIVE TorrentSelectionMode = 2
)

type TorrentSelection struct {
	Mode     TorrentSelectionMode
	Selected []int64
}

// NewTorrentSelection creates a TorrentSelection by parsing the arguments from
// an incoming request. This is because the 'ids' parameter may or may not be
// present.
func NewTorrentSelection(requestArguments *map[string]interface{}) (TorrentSelection, error) {
	ids, ok := (*requestArguments)["ids"]
	if !ok {
		return TorrentSelection{Mode: TSMODE_ALL, Selected: nil}, nil
	}

	switch ids := ids.(type) /* shadow with asserted type */ {
	case string:
		if ids == "recently-active" {
			return TorrentSelection{Mode: TSMODE_RECENTLY_ACTIVE, Selected: nil}, nil
		}
		return TorrentSelection{}, errors.New("Unexpected string in 'ids' parameter")

	case []interface{}:
		ret := TorrentSelection{Mode: TSMODE_SELECTED, Selected: make([]int64, len(ids))}
		for i := 0; i < len(ids); i += 1 {
			floatVal, ok := ids[i].(float64)
			if !ok {
				return TorrentSelection{}, fmt.Errorf("Unexpected type %T for ids[%d] entry", ids[i], i)
			}
			ret.Selected[i] = int64(floatVal)
		}
		return ret, nil

	default:
		return TorrentSelection{}, fmt.Errorf("Unexpected type %T for 'ids' parameter", ids)

	}
}
