package backendtest

import (
	"database/sql"
	"time"

	"code.justin.tv/video/spectre/backend"
)

var channels = map[int]backend.Channel{
	10: backend.Channel{
		ID:               10,
		Enabled:          "asdf",
		ActivePlaylistID: 1,
		Active:           true,
		StartTime:        time.Now().UTC(),
	},
	50: backend.Channel{
		ID:               50,
		Enabled:          "",
		ActivePlaylistID: 2,
		StartTime:        time.Now().UTC(),
	},
}

var playlists = map[int]backend.Playlist{
	1: backend.Playlist{
		ID:        1,
		ChannelID: 10,
		Version:   1,
	},
	2: backend.Playlist{
		ID:        2,
		ChannelID: 50,
		Version:   1,
	},
}

func (b *Backend) GetChannel(name int) (*backend.Channel, error) {
	if channel, found := channels[name]; found {
		return &channel, nil
	}
	return &backend.Channel{}, sql.ErrNoRows
}

func (b *Backend) GetChannelUncached(name int) (*backend.Channel, error) {
	if channel, found := channels[name]; found {
		return &channel, nil
	}
	return &backend.Channel{}, sql.ErrNoRows
}

func (b *Backend) UpdateChannel(values backend.ChannelParams) error {
	return nil
}

type Backend struct{}

func NewBackend() *Backend {
	return &Backend{}
}

func (b *Backend) GetPlaylists(channelID int) ([]backend.Playlist, error) {
	channelPlaylists := []backend.Playlist{}
	return channelPlaylists, nil
}

func (b *Backend) GetPlaylist(channelID int, id int) (*backend.Playlist, error) {
	if playlist, found := playlists[id]; found && playlist.ChannelID == channelID {
		return &playlist, nil
	}
	return &backend.Playlist{}, sql.ErrNoRows
}

func (b *Backend) CreatePlaylist(values backend.PlaylistParams) (*backend.Playlist, error) {
	for _, existingPlaylist := range playlists {
		if existingPlaylist.ChannelID == values.ChannelID {
			return &backend.Playlist{}, backend.ErrChannelAlreadyHasPlaylist
		}
	}

	return &backend.Playlist{
		ID:        100,
		ChannelID: values.ChannelID,
		Version:   1,
	}, nil
}

func (b *Backend) UpdatePlaylist(values backend.PlaylistParams) (*backend.Playlist, error) {
	playlist := backend.Playlist{
		ChannelID: values.ChannelID,
		ID:        values.ID,
		Playlist:  values.Playlist,
	}
	if values.ID == 1 || values.ID == 2 {
		return &playlist, nil
	} else {
		return nil, sql.ErrNoRows
	}
}

func (b *Backend) DeletePlaylist(channelID int, id int) error {
	_, err := b.GetPlaylist(channelID, id)
	return err
}

func (b *Backend) EnabledVodIDs() []int {
	return []int{1}
}
