/*
 * 1. Initialize File manager.
 * 2. Starts watching files if config is supplied.
 */
func NewFM(dbName string, configFile ...interface{}) (fm *FileManager, err error) {
	fm = &FileManager{
		updates:  make(chan updateMsg, 1),
		done:     make(chan bool),
		services: config.NewServices(dbName),
	}
	fm.stateMonitor(2 * time.Second)

	// this will recover all panic and destroy appropriate assets
	defer func() {
		if e := recover(); e != nil {
			fm.Destroy()
			err = e.(error)
			fm = nil
		}
	}()

	//TODO: should do something with logger
	if l == nil {
		l = logger.InitLogger(&logger.LogParams{LogPrefix: "[FM] "})
	}

	if configFile != nil {
		if watch, err := readConfigFile(configFile[0]); err != nil {
			panic(fmt.Errorf("unable to read config file: %v", err))
		} else {
			if watch == nil {
				panic(fmt.Errorf("%q key not found in config file", "watch"))
			}
			for _, pair := range watch {
				l.Println("Starting to watch: ", pair["source"], pair["target"])
				if err := fm.Watch(pair["source"], pair["target"]); err != nil {
					panic(fmt.Errorf("unable to watch %q: %v", pair["source"], err))
				}
			}
		}

	}
	return
}
	"github.com/Bnei-Baruch/mms-file-manager/logger"
	r "github.com/dancannon/gorethink"
	"log"
	"os"
	"time"
)

var (
	tables = []struct {
		name    string
		options r.TableCreateOpts
	}{
		{"files", r.TableCreateOpts{PrimaryKey: "file_name"}},
	}

	l *log.Logger = logger.InitLogger(&logger.LogParams{LogMode: "screen", LogPrefix: "[DB] "})
)

func InitDB(dbName string) (session *r.Session, err error) {

	var cursor *r.Cursor

	session, err = r.Connect(r.ConnectOpts{
		Address:  os.Getenv("RETHINKDB_URL"),
		Database: dbName,
		MaxIdle:  10,
		Timeout:  time.Second * 10,
	})

	if err != nil {
		l.Println("Connect", err)
func Logger(params *logger.LogParams) {
	l = logger.InitLogger(params)
}
		session, err = r.Connect(r.ConnectOpts{
			Address:  os.Getenv("RETHINKDB_URL"),
			Database: dbName,
			MaxIdle:  10,
			Timeout:  time.Second * 10,
		})

		if err != nil {
			log.Println(err)
			return
		}
	}

	dropDB()
	fm.Logger(&logger.LogParams{LogMode: "screen", LogPrefix: "[FM] "})
	l = logger.InitLogger(&logger.LogParams{LogMode: "screen", LogPrefix: "[FM-TEST] "})
})

var _ = AfterSuite(func() {
	dropDB()
})

func createTestFile(fileName string) {
	var (
		err error
		nf  *os.File
	)
	if nf, err = os.Create(fileName); err != nil {
		Fail(fmt.Sprintf("Unable to create file %s", fileName))
	}
	nf.Close()