package cn.superdesk.uniorder.common.queue.delayed;

import lombok.Getter;
import lombok.ToString;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Description: 延时任务
 * @Author: linjinyu
 * @CreateDate: 9/21/20 3:30 PM
 * @UpdateUser: linjinyu
 * @UpdateDate: 9/21/20 3:30 PM
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 */
@Getter
@ToString
public class DelayTaskAsync implements Delayed {


    final private DelayTaskBase data;

    final private long expire;

    /**
     * 构造延时任务
     *
     * @param data   业务数据
     * @param expire 任务延时时间(ms)
     */
    public DelayTaskAsync(DelayTaskBase data, long expire) {
        super();
        this.data = data;
        this.expire = expire + System.currentTimeMillis();
    }

//	public DelayTaskBase getData() {
//		return data;
//	}

//	public long getExpire() {
//		return expire;
//	}

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof DelayTaskAsync) {
            return this.data.getIdentifier().equals(((DelayTaskAsync) obj).getData().getIdentifier());
        }
        return false;
    }

//	@Override
//	public String toString() {
//		return "{" + "data:" + data.toString() + "," + "expire:" + new Date(expire) + "}";
//	}

    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(this.expire - System.currentTimeMillis(), unit);
    }

    @Override
    public int compareTo(Delayed o) {
        long delta = getDelay(TimeUnit.NANOSECONDS) - o.getDelay(TimeUnit.NANOSECONDS);
        return (int) delta;
    }

}
