package config

import (
	"io/ioutil"

	"github.com/BurntSushi/toml"
	"github.com/juju/errors"
	"github.com/ngaut/log"
	"github.com/pingcap/schrodinger/config"
)

// GetBuildConfig returns the buildConfig
func GetBuildConfig() *Config {
	return buildConfig
}

// buildConfig represents configuration of buildbot
var buildConfig = &Config{
	BaseConfig: BaseConfig{
		AgentBinaryAddr:     "http://download.pingcap.org/agent.tar.gz",
		DownloadAddr:        "http://fileserver.pingcap.net",
		DockerRegistryAddr:  "hub.pingcap.net/schrodinger",
		DockerRegistryAPI:   "hub.pingcap.net/api",
		SchrodingerRepoAddr: "https://github.com/pingcap/schrodinger.git",
		DefaultPlatform:     "centos7",
		Concurrency:         5,
	},

	Storage: config.Storage{
		Driver:       "mysql",
		Datasource:   "root:@(localhost:4000)/schrodinger",
		MaxIdleConns: 128,
	},
}

// Config of buildbot
type Config struct {
	BaseConfig BaseConfig     `toml:"base"`
	Storage    config.Storage `toml:"storage"`
}

// BaseConfig defines the config of buildManger
type BaseConfig struct {
	AgentBinaryAddr     string `toml:"agentBinaryAddr"`
	DownloadAddr        string `toml:"downloadAddr"`
	DockerRegistryAddr  string `toml:"dockerRegistryAddr"`
	DockerRegistryAPI   string `toml:"dockerRegistryAPI"`
	SchrodingerRepoAddr string `toml:"schrodingerRepoAddr"`
	DefaultPlatform     string `toml:"defaultPlatform"`

	// the count of concurrency worker and controls the number of running tasks
	Concurrency int `toml:"concurrency"`
}

// Load will parse variable into config object
func (c *Config) Load(filePath string) error {
	if filePath != "" {
		if err := parseConfigFromFile(filePath, c); err != nil {
			log.Errorf("parse config from file error %v", err)
			return errors.Trace(err)
		}
	}

	return nil
}

func parseConfigFromFile(filePath string, c *Config) error {
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return errors.Trace(err)
	}

	err = toml.Unmarshal(data, c)
	return errors.Trace(err)
}
