package executor

import (
	"encoding/json"
	"time"
)

const(
	CONDITION_IGNORE  = 9999
)

type TaskConf struct {
	Name string `json:"name"`
	Group string `json:"group"`
	Time []int `json:"time"`	// year, mon, day, wday, hour, min, sec
	Interval int64 `json:"interval"`
	Condition int32 `json:"condition"`
	Delay int64 `json:"delay"`
	Times int64 `json:"times"`
	Fn string `json:"fn"`
	Params interface{} `json:"params"`
}

func NewTaskConf(j string) (*TaskConf, error) {
	tc := &TaskConf{
		Condition: CONDITION_IGNORE,
	}

	err := json.Unmarshal([]byte(j), tc)
	if nil != err {
		return nil, err
	}
	return tc, nil
}

func (self *TaskConf)ValidTime() bool {
	l := len(self.Time)
	return l == 7
}

func (self *TaskConf)IsTimeFit(t time.Time) bool {
	if !self.ValidTime() {
		return false
	}
	return t.Second() == self.Time[6] &&
		t.Minute() == self.Time[5] &&
		t.Hour() == self.Time[4] &&
		(convertWeekdayIndex(t.Weekday()) == self.Time[3] || self.Time[3] == 0) &&
		(t.Day() == self.Time[2] || self.Time[2] == 0) &&
		(int(t.Month()) == self.Time[1] || self.Time[1] == 0) &&
		(t.Year() == self.Time[0] || self.Time[0] == 0)
}

func (self *TaskConf)ValidInterval() bool {
	return self.Interval > 0
}

func (self *TaskConf)ValidCondition() bool {
	return self.Condition != CONDITION_IGNORE
}

func (self *TaskConf)ValidDelay() bool {
	return self.Delay > 0
}

func (self *TaskConf)ValidTimes() bool {
	return self.Times > 0
}

func (self *TaskConf)GetFn()(IExecutor, error) {
	return RegisterGetFunc(self.Fn)
}

// convert weekday to int
// monday -- sunday  [1 -- 7]
func convertWeekdayIndex(weekday time.Weekday) int {
	if weekday == time.Sunday {
		return 7
	}
	return int(weekday)
}