import com.sun.lwuit.html.DocumentInfo;
import com.sun.lwuit.html.DocumentRequestHandler;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class HttpRequestHandler implements DocumentRequestHandler {

    static String getDomainForLinks(String url) {
        String domain = null;
        if (url.startsWith("file:")) {
            return "localhost"; // Just a common name to store local files under
        }
        int index = -1;
        if (url.startsWith("http://")) {
            index = 7;
        } else if (url.startsWith("https://")) {
            index = 8;
        }
        if (index != -1) {
            domain = url.substring(index);
            index = domain.indexOf('/');
            if (index != -1) {
                domain = domain.substring(0, index);
            }
        }
        return domain;
    }

    public InputStream resourceRequested(DocumentInfo docInfo) {
        InputStream is = null;
        String url = docInfo.getUrl();
        String linkDomain = getDomainForLinks(url);
        String params = docInfo.getParams();
        if ((!docInfo.isPostRequest()) && (params != null) && (!params.equals(""))) {
            url = url + "?" + params;
        }

        try {
            HttpConnection hc = (HttpConnection) Connector.open(url);
            String encoding = null;
            if (docInfo.isPostRequest()) {
                encoding = "application/x-www-form-urlencoded";
            }
            if (!docInfo.getEncoding().equals(DocumentInfo.ENCODING_ISO)) {
                encoding = docInfo.getEncoding();
            }
            String domain = linkDomain;
            domain = domain.substring(domain.indexOf('.'));

            if (encoding != null) {
                hc.setRequestProperty("Content-Type", encoding);
            }

            if (docInfo.isPostRequest()) {
                hc.setRequestMethod(HttpConnection.POST);
                byte[] paramBuf = params.getBytes();
                hc.setRequestProperty("Content-Length", "" + paramBuf.length);
                OutputStream os = hc.openOutputStream();
                os.write(paramBuf);
                os.close();
            }

            String contentTypeStr = hc.getHeaderField("content-type");
            if (contentTypeStr != null) {
                contentTypeStr = contentTypeStr.toLowerCase();
                if (docInfo.getExpectedContentType() == DocumentInfo.TYPE_HTML) { //We perform these checks only for text (i.e. main page), for images/css we just send what the server sends and "hope for the best"
                    if (contentTypeStr != null) {
                        if ((contentTypeStr.startsWith("text/")) || (contentTypeStr.startsWith("application/xhtml")) || (contentTypeStr.startsWith("application/vnd.wap"))) {
                            docInfo.setExpectedContentType(DocumentInfo.TYPE_HTML);
                        } else if (contentTypeStr.startsWith("image/")) {
                            docInfo.setExpectedContentType(DocumentInfo.TYPE_IMAGE);
                            hc.close();
                        } else {
                            hc.close();
                        }
                    }
                }

                if ((docInfo.getExpectedContentType() == DocumentInfo.TYPE_HTML) ||
                        (docInfo.getExpectedContentType() == DocumentInfo.TYPE_CSS)) { // Charset is relevant for HTML and CSS only
                    int charsetIndex = contentTypeStr.indexOf("charset=");
                    if (charsetIndex != -1) {
                        String charset = contentTypeStr.substring(charsetIndex + 8);
                        docInfo.setEncoding(charset.trim());
                    }
                }
            }
            int response = hc.getResponseCode();
            if (response / 100 == 3) { // 30x code is redirect
                String newURL = hc.getHeaderField("Location");
                if (newURL != null) {
                    hc.close();
                    docInfo.setUrl(newURL);
                    return resourceRequested(docInfo);
                }
            }
            is = hc.openInputStream();

        } catch (IOException e) {
            System.out.println("HttpRequestHandler->IOException: " + e.getMessage());
        } catch (IllegalArgumentException e) { // For malformed URL
            System.out.println("HttpRequestHandler->IllegalArgumentException: " + e.getMessage());
        }
        return is;
    }
}
