package main

import (
	"os"
	"strconv"
	"time"
)

type (
	DB interface {
		HistoryOf(IDU) map[IDQ][]Answer
		Next(IDU, IDQ) time.Time
		Question(IDQ) Question
		LastAnswer(IDU, IDQ) (IDA, Answer)
		Answer(IDA) Answer
		PushAnswer(IDU, IDQ, Renderable, bool) error
		UserResolution(IDU) int
		Close()
	}
	Question struct {
		Q        Renderable
		Solution []Renderable
		Clues    []Renderable
		Tags     []IDT
	}
	Answer struct {
		Q      IDQ
		A      Renderable
		TS     int64
		Author IDU
		Pass   bool
	}
	IDA        string
	IDQ        string
	IDU        string
	IDT        string
	Renderable string
)

var (
	CMD_PASS = "y"
	CMD_FAIL = "n"
	CMD_SKIP = "s"
	CMD_QUIT = "q"
)

func main() {
	if err := Main(); err != nil {
		panic(err)
	}
}

func Main() error {
	db, err := NewDB()
	if err != nil {
		return err
	}
	defer db.Close()
	if port, _ := strconv.Atoi(os.Getenv("PORT")); port > 0 {
		return HTTP(port, db)
	}
	return Terminal(db)
}

func NewDB() (DB, error) {
	return newYamlDB(os.Getenv("DB"))
}

func (q Question) Tagged(tag IDT) bool {
	for i := range q.Tags {
		if q.Tags[i] == tag {
			return true
		}
	}
	return false
}
