package main

import (
	"core"
	"log"
	"regexp"
	"strings"

	"github.com/chzyer/readline"
)

// Helper
type Param []string

func (p Param) String() string {
	var str = ""
	for i, v := range p {
		if i != 0 {
			str += ", "
		}
		str += "'" + v + "'"
	}
	return str
}

func main() {
	//mgo.SetDebug(true)
	//mgo.SetLogger(log.New(os.Stderr, "MGO: ", 0))

	rl, err := readline.New("> ")
	if err != nil {
		panic(err)
	}

	for {
		line, err := rl.Readline()
		if err == readline.ErrInterrupt {
			log.Println("Exiting...")
			return
		}
		// Process line
		//log.Println("Processing line", line)

		cmdParam := []string{}
		// Split line properly
		quotePart := strings.Split(line, "\"")
		re := regexp.MustCompile("\\s+")
		for i, p := range quotePart { // Even is normal odd is quoted
			if i&1 == 0 { // Even
				s := re.Split(strings.TrimSpace(p), -1)
				cmdParam = append(cmdParam, s...)
				continue
			}
			cmdParam = append(cmdParam, p) // Add full string
		}
		log.Println("Process cmds", len(cmdParam), Param(cmdParam))

		if cmdParam[0] == "user" {
			if len(cmdParam) == 1 {
				continue
			}
			// User Processor
			if cmdParam[1] == "new" {

				if len(cmdParam) != 6 {
					log.Println("Invalid param should be: user new [name] [description] [email] [passw]")
					continue
				}
				// ENV based config, docker friendly
				c := core.New()

				// Session on the core
				s := c.Session()

				s.User().NewUser(cmdParam[2], cmdParam[3], cmdParam[4], cmdParam[5])
				// Login:
				//u, err := s.Login("stdiopt@gmail.com", "1q2w3e")
				u, err := s.User().Login("admin", "1q2w3e")
				if err != nil {
					panic(err)
				}
				log.Println("User logged in:", u)

				//res := s.MustList()
				//log.Println("Res:", res)

			}
		}

	}

}
