package core

import (
	"fmt"
	"log"
	"os"

	mgo "gopkg.in/mgo.v2-unstable"
)

type Core struct {
	session *mgo.Session
	// Options..
}

func Demo() *Core {
	c := New()

	c.session.DB("mgo-test").C("users").DropCollection()
	var err error
	us := c.Session().User()
	if err = us.NewUser("admin", "Administration account", "admin@domain.tld", "pwd"); err != nil {
		log.Println("Error adding demo user", err)
	}
	if err = us.NewUser("user1", "user account", "user1@domain.tld", "pwd"); err != nil {
		log.Println("Error adding demo user", err)
	}
	if err = us.NewUser("user2", "user account", "user2@domain.tld", "pwd"); err != nil {
		log.Println("Error adding demo user", err)
	}
	if err = us.NewUser("user3", "user account", "user3@domain.tld", "pwd"); err != nil {
		log.Println("Error adding demo user", err)
	}

	return c
}

func New() *Core {
	mongoHost := os.Getenv("DBHOST")
	if mongoHost == "" {
		mongoHost = "mongodb" // Defaults to
	}
	log.Println("MongoHost", mongoHost)
	mongodsn := fmt.Sprintf("mongodb://%s", mongoHost)
	//session, err := mgo.Dial("mongodb://admin:1q2w3e@localhost/mgo-test")
	session, err := mgo.Dial(mongodsn)
	if err != nil {
		panic(err)
	}

	return &Core{session}
}

// Prepare everything

func (c *Core) Session() *Session {
	nsess := c.session.Copy()

	return &Session{nsess}
}
