package org.arkiwi.app.utility;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.arkiwi.app.interfaces.RssInterface;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

public class SNetwork implements RssInterface{
	public static final String LOG_TAG = "SNetwork";
	
    public static boolean isConnected(ConnectivityManager cm) {
        boolean connected = false;

        if (cm != null) {
            NetworkInfo[] netInfo = cm.getAllNetworkInfo();

            for (NetworkInfo ni : netInfo) {
            	Log.d(LOG_TAG, "type:"+ni.getTypeName()+" conn:"+ni.isConnected()
            			+" avv:"+ni.isAvailable() );
                if ((ni.getTypeName().equalsIgnoreCase("WIFI") || 
                	 ni.getTypeName().equalsIgnoreCase("MOBILE")) 
                	 && ni.isConnected() && ni.isAvailable()){
                	connected = true;
                	break;
                }
            }
        }

        return connected;
    }
    
    public static String doGet(String uri) {
    	String result = null;
    	
		HttpGet req = new HttpGet();
		DefaultHttpClient client = new DefaultHttpClient();
		try {
			URI targetUri = new URI(uri);
			req.setURI(targetUri);
			HttpResponse response = client.execute(req);
			InputStream content = response.getEntity().getContent();
			byte[] buffer = new byte[1024];
			int numRead = 0;
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			while ((numRead = content.read(buffer)) != -1) {
				baos.write(buffer, 0, numRead);
			}
			content.close();
			result = new String(baos.toByteArray());

		} catch (Exception e) {
			e.printStackTrace();
			try {
				String cause = e.getCause().toString();
				String[] cParts = cause.split("- ");
				result = cParts[1];
				Log.d(LOG_TAG,e.getCause().toString());
			} catch (Exception c) {
				result = HTTP_S_NET_ERR;
			} 
		}
		
		return result;
    }
}
