/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mobirent.communications;

import com.mobirent.abstracttags.Epitomize;
import com.mobirent.gui.ExceptionHandler;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

/**
 * Hálózatkezelésért felelős osztály.
 * @author  Budai Attila
 */
public class HTTPRequest {

    /**
     *  Az URL Cím, azt az oldalt címzi amivel létreszeretnénk hozni a kapcsolatot.
     */
    protected String baseURL = Epitomize.URL;// = Things.URL+Things.userName;
    private HttpConnection c;
    /**
     * Az adat amit küldeni szeretnénk.
     */
    protected String dataToSend;
    private String res = "";

    public HTTPRequest() {
    }

    /**
     * 
     * @param dataToSend a küldeni kívánt adat.
     * @param baseUrl az url ahová küldeni szeretnénk a @param dataToSend - et.
     */
    public HTTPRequest(String dataToSend) {
        this.dataToSend = "<m>" + dataToSend + "</m>";
    }

    /**
     * kérés küldése.
     * 
     * @throws com.mobut.realgui.MyException HttpConnection - hiba, vagy bmi más :D
     */
    public boolean sendRequest() throws ExceptionHandler {

        boolean ret = false;
        System.out.println("send2Rmsg : " + dataToSend);
        InputStream is = null;

        OutputStream os = null;
        int rc;
        try {
            System.out.println("1");
            c = (HttpConnection) Connector.open(baseURL, Connector.READ_WRITE);
            c.setRequestMethod(HttpConnection.POST);
            c.setRequestProperty("User-Agent",
                    "Profile/MIDP-2.0 Configuration/CLDC-1.0");
            System.out.println("1");
            c.setRequestProperty("Content-Type", "text/xml");

            System.out.println("1");
            os = c.openOutputStream();
            System.out.println("1");
            OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
            System.out.println("1");
            osw.write(dataToSend, 0, dataToSend.length());
            System.out.println("1");
            rc = c.getResponseCode();
            System.out.println("rc: "+ rc);
            if (rc != HttpConnection.HTTP_OK) {
                throw new Exception("HTTP response code: " + rc);
            }
            is = c.openInputStream();

            InputStreamReader iSR = new InputStreamReader(is, "UTF-8");
            int len = (int) c.getLength();
            if (len > 0) {
                int actual = 0;
                int bytesread = 0;
                char[] data = new char[len];
                while ((bytesread != len) && (actual != -1)) {
                    actual = iSR.read(data, bytesread, len - bytesread);
                    bytesread += actual;
                }
                process(data);
            } else {
                int ch;
                while ((ch = iSR.read()) != -1) {
                    process((byte) ch);
                }
            }
            ret = true;
        } catch (Exception e) {
            ret = false;
            throw new ExceptionHandler(e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    return ret;
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException ex) {
                    return ret;
                }
            }
            if (c != null) {
                try {
                    c.close();
                } catch (IOException ex) {
                    return ret;
                }
            }
        }
        System.gc();
        return ret;
    }

    /**
     * Válasz lekérdezése
     * @return String - A válasz.
     */
    public String getTextAnswer() {
        return res;
    }

    private void process(char[] data) {
        res = "";
        for (int i = 0; i < data.length; ++i) {
            res = res + data[i];
        }
    }

    private void process(byte b) {
        res = res + (char) b;
    }

    /**
     * Beállítjuk az adatot amit küldeni szeretnénk.
     *
     * @param dataToSend
     */
    public void setDataToSend(String dataToSend) {
        this.dataToSend =  dataToSend;
    }

    /**
     * Beállítja a server címét.
     * de mivel, minden egyes implementációnál az van,h. things.URL, így asszem felesleges :D
     *
     * @param url
     */
    public void setBaseURL(String url) {
        System.out.println("setURL:"+ url);
        baseURL = url;
    }
}