package com.ym.library.config;

import android.content.Context;
import android.os.Handler;
import android.os.HandlerThread;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public abstract class BaseChannel implements INativeAdAction {

    public volatile boolean isError = false;

    public volatile boolean isRefreshing = false;

    public volatile boolean isRequested;

    public volatile boolean isTimeOut = false;

    public long mWaitTime;

    public long mStartTime;

    public Context mContext;

    public int mCacheSize = 1;

    public Handler mPullHandler;

    public HandlerThread mThread;

    public static int MSG_DO_REFRESH = 111;

    public int mSid;

    public InnerCallBack.AdLoadCallback mLoadCallBack;
    public int retryCount = 0;

    public List<NativeADWrapper> mCacheList = Collections.synchronizedList(new ArrayList<NativeADWrapper>());

    public BaseChannel(Context context, int sid, int cacheSize, long wt) {
        this.mContext = context;
        this.mSid = sid;
        this.mCacheSize = cacheSize;
        this.mWaitTime = wt;
    }

    /**
     * 每个广告的时效性不同,故放到子类中处理
     *
     * @return
     */
    public NativeADWrapper doGetAD() {
        // 在子类中做处理
        if (mCacheList.size() > 0) {
            return mCacheList.get(0);
        } else {
            return null;
        }
    }

    public void setLoadListener(InnerCallBack.AdLoadCallback callback) {
        mLoadCallBack = callback;
    }

    /**
     * 在广告拉取onSuccess/onFailed时,调用判断是否需要继续填充(若允许一次拉多个则该方法会判断不触发)
     * 加入重试逻辑,拉取失败最多允许重试两次
     */
    public void ifContinue() {
        if (retryCount > 2) {
            return;
        }
        if (mCacheSize > mCacheList.size()) {
            retryCount++;
            doLoadAd();
        }
    }
}
