package com.bocloud.ims.entity.topology;

import com.alibaba.fastjson.JSONObject;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * @author tangcq
 * @since 2018-02-01
 */
@AllArgsConstructor
@NoArgsConstructor
public class RelationDelay implements Delayed {
    Logger logger = LoggerFactory.getLogger(RelationDelay.class);
    @Setter
    @Getter
    private InstanceRelation instanceRelation;
    @Setter
    @Getter
    private ModuleRelation moduleRelation;
    @Setter
    @Getter
    private Instance instance;
    @Getter
    private long createTime;
    //新丢进来的时间
    @Setter
    @Getter
    private long lastTime;
    @Setter
    @Getter
    private String bnameCloumn;

    public void setCreateTime(long createTime) {
        this.createTime = createTime;
        this.lastTime = createTime;
    }

    public RelationDelay(InstanceRelation instanceRelation, String bnameCloumn, Instance instance, ModuleRelation moduleRelation) {
        this.instanceRelation = instanceRelation;
        this.createTime = System.currentTimeMillis();
        this.lastTime = createTime;
        this.bnameCloumn = bnameCloumn;
        this.instance = instance;
        this.moduleRelation = moduleRelation;
        logger.info("延迟处理关系：" + JSONObject.toJSONString(instanceRelation));
    }

    /**
     * 比较谁创建的早 返回1 代表 目标 o晚
     */
    @Override
    public int compareTo(Delayed o) {
        RelationDelay target = (RelationDelay) o;
        return target.getCreateTime() - createTime > 0 ? 1 : 0;
    }

    /**
     * 延迟1分钟
     */
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert((lastTime + 1000L * 10L) - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

}
