package backend

import (
	"fmt"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
	"regexp"
)

type Backend struct{}

var db *sqlx.DB

type Backender interface {
	GetChannel(id int) (*Channel, error)
	GetChannelUncached(id int) (*Channel, error)
	UpdateChannel(values ChannelParams) error
	GetPlaylists(channelID int) ([]Playlist, error)
	GetPlaylist(channelID int, id int) (*Playlist, error)
	CreatePlaylist(values PlaylistParams) (*Playlist, error)
	UpdatePlaylist(values PlaylistParams) (*Playlist, error)
	DeletePlaylist(channelID int, id int) error
	EnabledVodIDs() []int
}

type MonitorBackend interface {
	AllChannels() ([]Channel, error)
	BatchMarkActive(ids []int)
	BatchMarkInactive(ids []int)
	GetPlaylist(channelID int, id int) (*Playlist, error)
	UpdateChannel(values ChannelParams) error
}

func NewBackend(pgConnInfo string) *Backend {
	var err error
	re := regexp.MustCompile(`password=\w+`)
	sanitizedConnInfo := re.ReplaceAllString(pgConnInfo, "password=****")
	fmt.Println("Opening DB connection: " + sanitizedConnInfo)
	db, err = sqlx.Connect("postgres", pgConnInfo)
	if err != nil {
		panic(err)
	}

	return &Backend{}
}
