package com.maniu.http;

import com.alibaba.fastjson.JSON;

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

/**
 * b包裹层  将请求对象包裹起来
 * @param <T>
 */
public class HttpTask<T> implements Runnable, Delayed {
    //请求对象
    private IHttpRequest iHttpRequest;
    //延迟的事件
    private long delayeTime;
    //失败的最大次数
    private int maxNum;

    public HttpTask(IHttpRequest iHttpRequest,String url,T reqeust,
                    JasonCallbackListener jasonCallbackListener) {
        this.iHttpRequest = iHttpRequest;
        this.iHttpRequest.setUrl(url);
        this.iHttpRequest.setListenner(jasonCallbackListener);
        //判断是否传参
        if(reqeust !=null ){
            String jasonStr = JSON.toJSONString(reqeust);
            try {
                this.iHttpRequest.setData(jasonStr.getBytes("utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        try {
            this.iHttpRequest.excute();
        }catch (Exception e){
            //执行重试机制
            ThreadManager.getInstance().addFailedTask(this);
        }

    }


    public long getDelayeTime() {
        return delayeTime;
    }

    public void setDelayeTime(long delayeTime) {
        this.delayeTime = delayeTime +System.currentTimeMillis();
    }

    public int getMaxNum() {
        return maxNum;
    }

    public void setMaxNum(int maxNum) {
        this.maxNum = maxNum;
    }

    @Override
    public long getDelay(TimeUnit timeUnit) {
        return timeUnit.convert(getDelayeTime()-System.currentTimeMillis(),
                TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed delayed) {
        return 0;
    }


    public IHttpRequest getiHttpRequest() {
        return iHttpRequest;
    }
}
