package kr.co.icontrols.ilp300_700.ethernet;

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

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class PingTest extends AsyncTask<Object, Void, String> {

    String TAG = "PingTest";

    boolean bLOG = true;   // true, false
    boolean bLOG_DEBUG = false;   // true, false
    boolean bLOG_INFO = true;   // true, false
    PingResult mPingResult;
    int TIMEOUT_PINGTEST = 3000;

    public PingTest() {
        LOG("[PingTestTask] ===== START =====");
    }

    private void LOG(String log) {
        if (bLOG) Log.v(TAG, log);
    }

    private void LOG_DEBUG(String log) {
        if (bLOG_DEBUG) Log.d(TAG, log);
    }

    private void LOG_INFO(String log) {
        if (bLOG_INFO) Log.i(TAG, log);
    }

    public boolean doPingTest(String strTargetIP) {
        try {
            LOG("[doPingTest] strTargetIP = " + strTargetIP);
            this.execute(strTargetIP);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] doPingTest(strTargetIP)");
            e.printStackTrace();
            return false;
        }
    }

    @Override
    protected String doInBackground(Object... params) {
        try {
            String TargetIP = (String) params[0];
            LOG("[PingTest] TargetIP = " + TargetIP);
            InetAddress TargetIA = InetAddress.getByName(TargetIP);
            if (TargetIA.isReachable(TIMEOUT_PINGTEST)) {
                return "Reachable";
            } else {
                return "Unreachable";
            }
        } catch (UnknownHostException e) {
            Log.e(TAG, "[UnknownHostException] PingTest.doInBackground(params)");
            e.printStackTrace();
            return "UnknownHostException";
        } catch (IOException e) {
            Log.e(TAG, "[IOException] PingTest.doInBackground(params)");
            e.printStackTrace();
            return "IOException";
        } catch (IllegalArgumentException e) {
            Log.e(TAG, "[IllegalArgumentException] PingTest.doInBackground(params)");
            e.printStackTrace();
            return "IllegalArgumentException";
        } catch (Exception e) {
            Log.e(TAG, "[Exception] PingTest.doInBackground(params)");
            e.printStackTrace();
            return "Exception";
        }
    }

    @Override
    protected void onPostExecute(String result) {
        try {
            LOG("[PingTestTask.onPostExecute] result = " + result);
            mPingResult.onResult(result);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] PingTest.doInBackground(params)");
            e.printStackTrace();
        }
    }

    public interface PingResult {
        void onResult(String Result);
    }
}