package com.kfb.kfbv1.model;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.HttpGet;
import com.loopj.android.http.SyncHttpClient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.UnknownHostException;

import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.HttpClient;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;


public class KfbHttpRequest {
    private  KfbGate mGate;
    static Handler handler = KfbModel.getData().handler;
    public  static String outS;
    private static String muri;
    private static SyncHttpClient client;
    private static AsyncHttpClient client1= new AsyncHttpClient();

    public String getTest(String aUrl)
    {
        client = new SyncHttpClient();
        try {
            String uri = aUrl;
            muri = uri;
             client.get(uri, new AsyncHttpResponseHandler() {
                @Override
                public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                    outS = new String(responseBody);
                    KfbModel.getData().tekser =outS;
                    KfbModel.getData().error = false;
                    //KfbModel.getData().progresok=true;

                  //  KfbModel.getData().textViewout.setText(outS);
                }

                @Override
                public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                    outS = "ERROR"+ error.getMessage();
                    KfbModel.getData().tekser =outS;
                    KfbModel.getData().error = true;
                   // KfbModel.getData().progresok=true;

                  // KfbModel.getData().textViewout.setText(outS);

                }

                 @Override
                 public void onRetry(int retryNo) {
                     super.onRetry(retryNo);
                     KfbModel.getData().tekser =outS;
                     KfbModel.getData().error = true;
                 }
             });
            return  outS;
        }catch (Exception e)
        {
            Log.e("HttpClient",e.getMessage());
            return "";
        }
    }
    public void checkIP(KfbGate aGate)
    {
        InetAddress in;
        in = null;
        // Definimos la ip de la cual haremos el ping
        try {
            URL u = new URL(aGate.getmAdres());

            in = InetAddress.getByName(u.getHost());
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        // Definimos un tiempo en el cual ha de responder
        try {
            if (in.isReachable(500)) {
            //    info.setText("Responde OK");
                aGate.setmNoPing(false);
            } else {
                LogFile.appendLog("Blad polaczenia  "+ muri);
                aGate.setmNoPing(true);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            aGate.setmNoPing(true);
        }
    }
    public static void getRequest1(KfbGate aGate) {
        HttpClient httpclient = new DefaultHttpClient();
        String uri = aGate.getmAdres();
        muri = uri;
        HttpGet httpget = new HttpGet(muri);

        // Execute the request
        HttpResponse response;
        try {
            response = httpclient.execute(httpget);
            // Examine the response status
            //Log.i("Praeda",response.getStatusLine().toString());

            // Get hold of the response entity
            HttpEntity entity = response.getEntity();
            // If the response does not enclose an entity, there is no need
            // to worry about connection release

            if (entity != null) {

                // A Simple JSON Response Read
                InputStream instream = entity.getContent();
                String result= convertStreamToString(instream);
                outS = result;
                KfbModel.getData().tekser =outS;
                KfbModel.getData().error = false;
             //  LogFile.appendLog("Mam dane ");
                instream.close();
            }


        } catch (Exception e) {}
    }
    private static String convertStreamToString(InputStream is) {
        /*
         * To convert the InputStream to String we use the BufferedReader.readLine()
         * method. We iterate until the BufferedReader return null which means
         * there's no more data to read. Each line will appended to a StringBuilder
         * and returned as String.
         */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return sb.toString();
    }

    public void getRequest(KfbGate aGate) {
        mGate = aGate;
         LogFile.appendLog("Wykonuje polaczenie ");
        client = new SyncHttpClient();
        try {
            String uri = aGate.getmAdres();
            muri = uri;
         client.get(uri, new AsyncHttpResponseHandler() {
             @Override
             public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                 outS = new String(responseBody);
                 KfbModel.getData().tekser =outS;
                 KfbModel.getData().error = false;
                 LogFile.appendLog("Mam dane ");
             }

             @Override
             public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                 outS = "ERROR"+ error.getMessage();
                 KfbModel.getData().tekser =outS;
                 KfbModel.getData().error = true;
                 LogFile.appendLog("Blad polaczenia  "+ muri);
             }
             @Override
             public void onRetry(int retryNo) {
                 super.onRetry(retryNo);
                 KfbModel.getData().tekser =outS;
                 KfbModel.getData().error = true;
                 LogFile.appendLog("Ponawiam  "+ retryNo);

             }
         });


        }catch (Exception e)
        {
            Log.e("HttpClient",e.getMessage());
        }
    }
}


