package detail

import (
	"dbackup/logging"
	"github.com/kardianos/service"
	"github.com/robfig/cron/v3"
	"os"
	"path/filepath"
	"runtime"
	"strings"
	"time"
)

func InitLogger() {
	curr, e := filepath.Abs(filepath.Dir(os.Args[0]))
	if e != nil {
		curr = filepath.Join(os.TempDir(), "dbackup.log")
	} else {
		curr = filepath.Join(curr, "log")
		_ = os.MkdirAll(curr, os.ModePerm)
		curr = filepath.Join(curr, "dbackup.log")
	}

	if runtime.GOOS == "windows" {
		curr = strings.ReplaceAll(curr, "\\", "/")
	}

	e = log.Init(&log.Logger{
		FileName:     curr,
		RollSize:     1 << 30,
		RollInterval: time.Hour * 30,
		Level:        log.DEBUG,
		PanicOnFatal: true,
	})
}

type Job interface {
	AddTask(*Task) error
}

type Task struct {
	Ch   chan struct{}
	Cron *cron.Cron
}

func (t *Task) Start(srv service.Service) error {
	log.Info("starting...")
	go t.Run()
	return nil
}

func (t *Task) Run() {
	log.Info("running...")
	t.Cron.Start()
	<-t.Ch
	log.Info("stopped")
	t.Cron.Stop()

}

func (t *Task) Stop(srv service.Service) error {
	log.Info("stopping...")
	t.Cron.Stop()
	t.Ch <- struct{}{}
	return nil
}

func (t *Task) AddTask(task Job) error {
	return task.AddTask(t)
}