package orm

import (
	"fmt"
	"net/http"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

type IDer interface {
	GetID() uint
}

type Timetable [][]Activity

type Person interface {
	GetCredential() *Credential
}

type Address struct {
	City    string
	Street  string
	ZipCode string
	Country string
}

type Location struct {
	Id      string
	Name    string
	Address *Address
}

type Room struct {
	Id       string
	Name     string
	Capacity int
	Location *Location
}

type Desk struct {
	Id       string
	Name     string
	Students []*Student
	Teacher  *Teacher
}

type GetFn func(map[string]string) (interface{}, error)
type PostFn func(map[string]string, *http.Request) (IDer, error)

var currDB *gorm.DB

func New(connection string) (*gorm.DB, error) {
	db, err := gorm.Open("mysql", connection)
	if err != nil {
		return nil, err
	}
	return db, nil
}

func Use(db *gorm.DB) {
	currDB = db
}

func DB() *gorm.DB {
	return currDB
}

func AutoMigrate() {
	if err := currDB.AutoMigrate(
		&School{},
		&Subject{},
		&Teacher{},
		&Class{},
		&Activity{},
		&Department{},
		&Student{},
		&Office{},
		&Administrative{},
		&Document{},
		&Job{},
		&File{},
	).Error; err != nil {
		panic(err)
	}

}

func GetFunc(path string) (GetFn, error) {
	fn, ok := Get[path]
	if !ok {
		return nil, fmt.Errorf("Can't map %s!", path)
	}

	return fn, nil
}

func PostFunc(path string) (PostFn, error) {
	fn, ok := Post[path]
	if !ok {
		return nil, fmt.Errorf("Can't map %s!", path)
	}

	return fn, nil
}

func GetNothing(args map[string]string) (interface{}, error) {
	return nil, nil
}

func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
	return nil, nil
}
