package main

import (
	"encoding/json"
	"errors"
	"fmt"
	"os"

	// _ "github.com/mattn/go-sqlite3"

	"git.tilde.town/tildetown/town/towndb"
)

// this command adds a new user to /town/var/town.db. it's meant to be invoked
// by the welcome binary upon successfully creating a new user account

func main() {
	tdb, err := towndb.ConnectDB()
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}

	userData, err := parseInput(os.Stdin)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(2)
	}

	if err = validateInput(userData); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(3)
	}

	if err = userData.Insert(tdb); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(4)
	}
}

func validateInput(userData towndb.TownUser) error {
	if userData.Username == "" {
		return errors.New("no username")
	}

	if len(userData.Emails) == 0 {
		return errors.New("no email set")
	}

	for _, e := range userData.Emails {
		if e == "" {
			return errors.New("blank email in email list")
		}
	}

	if userData.IsAdmin {
		return errors.New("please stop")
	}

	if userData.State != towndb.StateActive {
		return errors.New("bad state")
	}

	return nil
}

func parseInput(stdin *os.File) (u towndb.TownUser, err error) {
	var n int
	input := make([]byte, 3000) // arbitrary
	if n, err = stdin.Read(input); err != nil {
		return
	}
	if n == 0 {
		err = errors.New("nothing passed on input")
		return
	}
	err = json.Unmarshal(input[0:n], &u)
	return
}
