package config

import (
	"github.com/spf13/viper"
)

type Config struct {
	Chain33  Chain33   `toml:"chain33" json:"chain33"`
	DB       *DB       `toml:"db" json:"db,omitempty"`
	Services []Service `toml:"services" json:"services"`
	Router   Router    `toml:"router" json:"router"`
	Log      Log       `toml:"log" json:"log"`
}

type Log struct {
	Dir          string `toml:"dir" json:"dir"`
	Filename     string `mapstructure:"filename" json:"filename"`
	ReportCaller bool   `mapstructure:"report_caller"`
	Level        string `mapstructure:"level" json:"level"` // NoLevel:0, trace:1, debug:2, info:3, warn:4, error:5, off:6
}

type Router struct {
	FromChain string `mapstructure:"from_chain" json:"from_chain"`
	ToChain   string `mapstructure:"to_chain" json:"to_chain"`
}

type DB struct {
	// 数据存储格式名称，目前支持mavl,kvdb,kvmvcc,mpt
	Name string ` toml:"name"  json:"name,omitempty"`
	// 数据存储驱动类别，目前支持leveldb,goleveldb,memdb,gobadgerdb,ssdb,pegasus
	Driver string `toml:"driver" json:"driver,omitempty"`
	// 数据文件存储路径
	DbPath string `toml:"db_path" json:"db_path,omitempty"`
	// Cache大小
	DbCache int32 `toml:"db_cache" json:"db_cache,omitempty"`
}

type Chain33 struct {
	Title         string `toml:"title" json:"title"`
	Addr          string `toml:"addr" json:"addr"`
	Name          string `toml:"name" json:"name"`
	PrivateKey    string `mapstructure:"private_key" toml:"private_key" json:"private_key"`
	ChainID       int32  `mapstructure:"chain_id" json:"chain_id"`
	StartHeight   int64  `mapstructure:"start_height" json:"start_height"` // 起始高度
	HeightDiff    int64  `mapstructure:"height_diff" json:"height_diff"`   // 高度差
	Fee           int64  `mapstructure:"Fee" json:"Fee"`                   // 单笔交易的手续费
	EventFilter   string `mapstructure:"event_filter" toml:"event_filter" json:"event_filter"`
	TimeoutHeight int64  `mapstructure:"timeout_height" json:"timeout_height"`
	IsTest        bool   `mapstructure:"is_test" json:"is_test"`
}

type Service struct {
	ID   string `toml:"id" json:"id"`
	Name string `toml:"name" json:"name"`
	Type string `toml:"type" json:"type"`
}

func DefaultConfig() *Config {
	return &Config{
		Chain33: Chain33{
			Addr:        "40.125.164.122:8801",
			Name:        "chain33",
			PrivateKey:  "",
			ChainID:     1,
			StartHeight: 3,
			HeightDiff:  6,
			Fee:         1e5,
		},
		DB: &DB{
			Name:    "blockchain",
			Driver:  "leveldb",
			DbPath:  "./blockchain",
			DbCache: 100,
		},
		Router: Router{
			FromChain: "paracross",
			ToChain:   "evmxgo",
		},
		Log: Log{
			Level: "info",
		},
		Services: nil,
	}
}

func UnmarshalConfig(configPath string) (*Config, error) {
	viper.SetConfigFile(configPath)
	viper.SetConfigType("toml")
	if err := viper.ReadInConfig(); err != nil {
		return nil, err
	}

	config := DefaultConfig()

	if err := viper.Unmarshal(config); err != nil {
		return nil, err
	}

	return config, nil
}
