package rest

import (
	"fmt"
	"net/url"
	"strings"
)

type Config struct {
	Driver   string            `json:"driver"`
	Filename string            `json:"filename"`
	Host     string            `json:"host"`
	Port     int               `json:"port"`
	Username string            `json:"username"`
	Password string            `json:"password"`
	Database string            `json:"database"`
	Params   map[string]string `json:"params"`
}

func (cfg *Config) ParseDSN() string {
	if cfg.Driver == "sqlite3" {
		return cfg.Filename
	} else if cfg.Driver == "mysql" {
		ps := map[string]string{
			"charset":   "utf8",
			"parseTime": "True",
			"loc":       "Local",
		}
		if cfg.Params != nil {
			for k, v := range cfg.Params {
				ps[k] = v
			}
		}
		u := url.Values{}
		for k, v := range ps {
			u.Set(k, v)
		}
		return fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?",
			cfg.Username,
			cfg.Password,
			cfg.Host,
			cfg.Port,
			cfg.Database) + u.Encode()
	} else if cfg.Driver == "postgres" {
		var s string
		if cfg.Params != nil {
			for k, v := range cfg.Params {
				s += k + "=" + v + " "
			}
		}
		s = strings.TrimRight(s, " ")
		return fmt.Sprintf("host=%s port=%d user=%s dbname=%s password=%s",
			cfg.Host,
			cfg.Port,
			cfg.Username,
			cfg.Database,
			cfg.Password) + s
	}
	return ""
}
