package model

import (
	"time"

	"github.com/google/uuid"
	"gopkg.in/ini.v1"
	"virjar.com/majora-go/common"
)

type Redial struct {
	Command        string        `ini:"command" json:"command"`
	ExecPath       string        `ini:"exec_path" json:"exec_path"`
	RedialDuration time.Duration `ini:"redial_duration" json:"redial_duration"`
	WaitTime       time.Duration `ini:"wait_time" json:"wait_time"`
}

type Extra struct {
	Account string `ini:"account" json:"account"`
}

type Configure struct {
	LogLevel         string        `ini:"log_level" json:"log_level"`
	PprofPort        int           `ini:"pprof_port" json:"pprof_port"`
	TunnelAddr       string        `ini:"tunnel_addr" json:"tunnel_addr"`
	DNSServer        string        `ini:"dns_server" json:"dns_server"`
	LocalAddr        string        `ini:"local_ip" json:"local_ip"`
	ReconnInterval   time.Duration `ini:"reconn_interval" json:"reconn_interval"`
	ClientID         string        `ini:"client_id" json:"client_id"`
	NetCheckInterval time.Duration `ini:"net_check_interval" json:"net_check_interval"`
	NetCheckUrl      string        `ini:"net_check_url" json:"net_check_url"`
	Extra            Extra         `ini:"extra" json:"extra"`
	Redial           Redial        `ini:"redial" json:"redial"`
}

const (
	reconninterval = time.Second * 10
)

func NewDefMajoraConf() *Configure {
	return &Configure{
		LogLevel:       "info",
		PprofPort:      0,
		TunnelAddr:     common.DefNatAddr,
		DNSServer:      common.DNSServer, //nolint:typecheck
		ReconnInterval: reconninterval,
		ClientID:       uuid.New().String(),
		Extra: Extra{
			Account: uuid.New().String(),
		},
		Redial: Redial{
			RedialDuration: reconninterval,
		},
	}
}

func InitConf(path string) *Configure {
	conf := NewDefMajoraConf()
	if err := ini.MapTo(conf, path); err != nil {
		panic(err)
	}
	return conf
}

func (r Redial) Valid() bool {
	if len(r.Command) == 0 {
		return false
	}

	if len(r.ExecPath) == 0 {
		return false
	}

	if r.RedialDuration <= 0 {
		return false
	}
	return true
}
