package com.maniu.http;

import android.util.Log;

import com.alibaba.fastjson.JSON;

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


/**
 * 请求任务
 * 封装请求对象的参数  以及创建请求线程
 */
public class HttpTask<T> implements Runnable, Delayed {
    //持有请求对象
    private IHttpRequest iHttpRequest;
    //最多失败多少次 超过就放弃执行
    private int maxFaildNum;
    //设置每次失败之后的等待时间
    private long delayTime;

    public HttpTask(IHttpRequest iHttpRequest,String url,T requestData,
                    CallBackListenner callBackListenner){
        this.iHttpRequest = iHttpRequest;
        this.iHttpRequest.setUrl(url);
        this.iHttpRequest.setListener(callBackListenner);
        //判断是否传送了数据给服务器
        if(requestData !=null){
            String jsonStr = JSON.toJSONString(requestData);
            try {
                this.iHttpRequest.setData(jsonStr.getBytes("UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void run() {
        try{
            this.iHttpRequest.excute();
        }catch (Exception e){

            //再重新去发送这个请求
            ThreadManager.getInstance().addFailedTask(this);
        }
    }

    public int getMaxFaildNum() {
        return maxFaildNum;
    }

    public void setMaxFaildNum(int maxFaildNum) {
        this.maxFaildNum = maxFaildNum;
    }

    public long getDelayTime() {
        return delayTime;
    }

    public void setDelayTime(long delayTime) {
        this.delayTime = delayTime+System.currentTimeMillis();
    }

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

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

    public IHttpRequest getiHttpRequest() {
        return iHttpRequest;
    }
}
