//
//  tank
//
//  Import and Playlist Daemon for autoradio project
//
//
//  Copyright (C) 2017-2018 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of tank.
//
//  tank is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  tank is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with tank. If not, see <http://www.gnu.org/licenses/>.
//

package store

import (
	"errors"
	"os"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	_ "github.com/jinzhu/gorm/dialects/postgres"
	// _ "github.com/jinzhu/gorm/dialects/sqlite"
	// _ "github.com/jinzhu/gorm/dialects/mssql"
)

type Store struct {
	revision string
	db       *gorm.DB
	basePath string
}

//
// Initialization and Destruction
//

func openDB(cfg DBConfig) (db *gorm.DB, err error) {
	if db, err = gorm.Open(cfg.Type, cfg.Connection); err != nil {
		return nil, errors.New("gorm.open(): " + err.Error())
	}
	// TODO: make debugging configurable
	//db.LogMode(true)

	if err = db.DB().Ping(); err != nil {
		return nil, errors.New("gorm.Ping(): " + err.Error())
	}

	return
}

func NewStore(cfg *Config) (*Store, error) {
	if _, err := os.Stat(cfg.BasePath); err != nil {
		return nil, errors.New("cant't open store base path: " + err.Error())
	}

	db, err := openDB(cfg.DB)
	if err != nil {
		return nil, err
	}

	st := &Store{"", db, cfg.BasePath}
	if err = st.initDBModel(); err != nil {
		return nil, err
	}

	return st, nil
}

func (st *Store) GetRevision() string {
	return st.revision
}

func (st *Store) Close() {
	st.db.Close()
}