package com.mogo.telematic.discovery;

import android.os.AsyncTask;
import android.util.Log;

import com.mogo.telematic.discovery.bean.HostBean;
import com.mogo.telematic.discovery.bean.NetInfo;

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

/**
 * @author mogoauto
 */
public abstract class AbstractDiscoveryTask extends AsyncTask<Void, HostBean, Void> {

    private static final String TAG = "AbstractDiscoveryTask";
    protected int hosts_done = 0;

    private ArrayList<HostBean> hostList = new ArrayList<>();

    private List<DiscoveryDriverListener> mDiscoveryDriverListenerList = new ArrayList<>();

    protected long ip;
    protected long start = 0;
    protected long end = 0;
    protected long size = 0;

    public void addDiscoveryDriverListener(DiscoveryDriverListener discoveryDriverListener) {
        mDiscoveryDriverListenerList.add(discoveryDriverListener);
    }

    public void removeDiscoveryDriverListener(DiscoveryDriverListener discoveryDriverListener) {
        mDiscoveryDriverListenerList.remove(discoveryDriverListener);
    }

    public void setNetwork(long ip, long start, long end) {
        this.ip = ip;
        this.start = start;
        this.end = end;
        Log.d(TAG, "setNetwork: ip=" + NetInfo.getIpFromLongUnsigned(ip)
                + ", start=" + NetInfo.getIpFromLongUnsigned(start)
                + ", end=" + NetInfo.getIpFromLongUnsigned(end)
        );
    }

    @Override
    abstract protected Void doInBackground(Void... params);

    @Override
    protected void onProgressUpdate(HostBean... host) {
        Log.d(TAG, "onProgressUpdate: isCancelled=" + isCancelled());
        if (hostList != null) {
            if (!isCancelled()) {
                if (host[0] != null) {
                    hostList.add(host[0]);
                }
            }
        }
    }

    @Override
    protected void onPostExecute(Void unused) {
        Log.d(TAG, "onPostExecute: 完成扫描，hostList=" + hostList);
        if (mDiscoveryDriverListenerList != null) {
            for (DiscoveryDriverListener discoveryDriverListener : mDiscoveryDriverListenerList) {
                discoveryDriverListener.onSuccess(hostList);
            }
        }
    }

    @Override
    protected void onCancelled() {
        Log.d(TAG, "onCancelled: 取消扫描");
        if (mDiscoveryDriverListenerList != null) {
            for (DiscoveryDriverListener discoveryDriverListener : mDiscoveryDriverListenerList) {
                discoveryDriverListener.onCancel();
            }
        }
        super.onCancelled();
    }
}
