package com.ericsson.uecontrol.core.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import android.os.Handler;
import com.ericsson.uecontrol.gui.MainActivity;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by ezivkoc on 2014-09-18.
 */
public class UrlUtil {
    private static final Logger log = Logger.getLogger(UrlUtil.class);

    public static URLConnection getURLConnection(URL url) throws IOException {
        if(!isNetworkAvailable())
            throw new IOException("No Data Network Available");

        final URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(3000);
        connection.setUseCaches(false);

        /*new Thread(new Runnable() {
            public void run() {
                try{Thread.sleep(5000);}catch(Exception e){};
                log.error("Force disconnect URLConnection");
                connection.
            }
        }).start();*/
        connection.connect();

        return connection;
    }

    public static boolean isNetworkAvailable() {
        ConnectivityManager cm = (ConnectivityManager)
                MainActivity.getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        // if no network is available networkInfo will be null
        // otherwise check if we are connected
        if (networkInfo != null && networkInfo.isConnected()) {
            return true;
        }
        return false;
    }
}
