package conf

import (
	"encoding/json"
	"github.com/go-resty/resty/v2"
	"io"
	"os"
	"strings"
)

type MatchRule struct {
	Domain []string
	Ip     []string
}

type Conf struct {
	path      string
	Disable   bool        `json:"Disable"`
	UpdateUrl string      `json:"UpdateUrl"`
	Checker   CheckerConf `json:"Checker"`
	Parser    ParserConf  `json:"Parser"`
}

func New(path string) *Conf {
	return &Conf{
		path:    path,
		Checker: newCheckerConf(),
		Parser:  newParserConf(),
	}
}

func (c *Conf) LoadConfig() error {
	var f io.ReadCloser
	var err error
	if strings.HasPrefix(c.path, "http") {
		var r *resty.Response
		r, err = resty.New().SetDoNotParseResponse(true).R().Get(c.path)
		if err == nil {
			f = r.RawResponse.Body
		}
	} else {
		f, err = os.Open(c.path)
	}
	if err != nil {
		return err
	}
	defer f.Close()
	err = json.NewDecoder(f).Decode(c)
	if err != nil {
		return err
	}
	return nil
}
