package action

import (
	"context"
	"errors"
	"fmt"
	"strconv"
	"time"

	ntf "jiraport/service/notification"
	"jiraport/service/timer"
)

type TimeoutCommand struct {
	timer *timer.Timer
}

func NewTimeoutCommand(timer *timer.Timer) (*TimeoutCommand, error) {
	return &TimeoutCommand{timer: timer}, nil
}

func (cmd *TimeoutCommand) Exec(ctx context.Context, actionExecInfo *ntf.NotificationActionExecInfo, args ...string) (bool, error) {
	if len(args) == 0 {
		return false, errors.New("timeout function require one parameter")
	}
	dura, err := strconv.Atoi(args[0])
	if err != nil {
		return false, fmt.Errorf("parse args error, %w", err)
	}
	if dura <= 0 {
		return false, errors.New("bad duration value")
	}

	future := cmd.timer.AsyncSchedule(time.Duration(dura)*time.Second, actionExecInfo)
	var ret interface{}
	select {
	case <-ctx.Done():
		return false, contextDoneErr
	case ret = <-future:
	}

	_, ok := ret.(*ntf.NotificationActionExecInfo)
	if !ok {
		return false, errors.New("bad value returned from scheduler")
	}
	return true, nil
}
