package collector

import (
	"git.loafle.net/overflow/overflow_probe/discovery/discovery"
	"git.loafle.net/overflow/overflow_probe/discovery/discovery/types/timestamp"
	log "github.com/cihub/seelog"
	"os/exec"
	"sync"
)

type Collector struct {
	stop chan bool `json:"-"`

	ID          int                 `json:"id,omitempty"`
	ProductId   string              `json:"productId"`
	Version     string              `json:"version"`
	ConfigPath  string              `json:"configPath"`
	InstallDate timestamp.Timestamp `json:"installDate"`
	UpdateDate  timestamp.Timestamp `json:"updateDate"`
}

var coll *Collector
var once sync.Once

func Start() *Collector {

	once.Do(func() {
		coll = &Collector{}
		coll.info()
	})
	coll.start()

	return coll
}

func Stop() {
	log.Info("Collector has stopped.")
}

func (c *Collector) start() {
	go coll.run()
}

func (c *Collector) run() {
	log.Info("Collector is now running.")

	fin := make(chan bool, 1)
	c.stop = make(chan bool)

	discovery.Discover(fin)

	if <-fin {
		log.Info("Discovery has finished.")
	}
}

func (c *Collector) info() {

	uuid, err := exec.Command("uuidgen").Output()
	if err != nil {
		log.Error(err)
	}
	c.ProductId = string(uuid)
	c.Version = "1.0"
	c.ConfigPath = "/root"
	c.InstallDate = timestamp.Now()
	c.UpdateDate = timestamp.Now()
}
