package com.netfluke.sergey.uploader;

import android.app.Activity;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.net.ssl.HttpsURLConnection;

/* This code does not check permissions. Yours should! */

public class MainActivity extends AppCompatActivity {
    private Handler dl;
    private String req;
    private Activity ctx;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dl = new Handler();
        // req = buildJSONRequest();
        ctx = this;
    }

    public void doGet(View v){

        EditText et = findViewById(R.id.editText);
        req = et.getText().toString();

        new Thread(new Runnable() {

            String res = null; // closed over by the post()-ed run().

            @Override
            public void run() {
                try {
                    URL url = new URL("http://cs65.cs.dartmouth.edu/profile.pl?" + req);
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    // For info on configurable headers of HTTP:
                    // https://developer.android.com/reference/java/net/HttpURLConnection.html

                    try {
                        // conn.setDoOutput(true);  this is a GET, they don't have a body
                        conn.setRequestMethod("GET");

                        // we want to see strings going back and forth, don't compress them
                        conn.setRequestProperty("Accept-Encoding", "identity");

                        InputStream in = new BufferedInputStream(conn.getInputStream());
                        res = readStream(in);
                    } finally {
                        conn.disconnect();
                    }
                }
                catch( Exception e){
                    Log.d("THREAD", e.toString());
                }

                Log.d("NET GET", res);
                postResultsToUI(res);
            }
        }).start();
    }

    public void doPost(View v){

        EditText et = findViewById(R.id.editText);
        req = et.getText().toString();

        new Thread(new Runnable() {

            String res = null; // closed over by the post()-ed run().

            @Override
            public void run() {
                try {
                    URL url = new URL("http://cs65.cs.dartmouth.edu/profile.pl");
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

                    // For info on configurable headers of HTTP:
                    // https://developer.android.com/reference/java/net/HttpURLConnection.html

                    try {
                        conn.setDoOutput(true);
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Content-Type", "application/json");

                        // we want to see strings going back and forth, don't compress them
                        conn.setRequestProperty("Accept-Encoding", "identity");

                        // This doesn't work with my server: CGI.pm ignores chunked requests
                        //conn.setRequestProperty("Transfer-Encoding", "chunked");
                        //conn.setChunkedStreamingMode(0); // we don't know how much data we'll be sending in the body

                        // we must know exactly what the request body is
                        conn.setFixedLengthStreamingMode(req.length());

                        OutputStream out = new BufferedOutputStream(conn.getOutputStream());
                        out.write(req.getBytes());
                        out.flush();
                        out.close();

                        InputStream in = new BufferedInputStream(conn.getInputStream());
                        res = readStream(in);
                    }
                    catch(Exception e){
                        Log.d("THREAD", e.toString());
                    } finally {
                        conn.disconnect();
                    }
                }
                catch( Exception e){
                    Log.d("THREAD", e.toString());
                }

                if( res!= null ) {
                    Log.d("NET POST", res);
                    postResultsToUI(res);
                }
                else{
                    Log.d("NET ERR", "empty result");
                }
            }
        }).start();
    }

    private void postResultsToUI(final String res){
        dl.post(new Runnable() {
            @Override
            public void run() {
                TextView tv = ctx.findViewById(R.id.txt);
                if( res == null )
                    tv.setText("Connection failed");
                else
                    tv.setText(res);
            }
        });
    }

    private String readStream(InputStream in) throws IOException {
        BufferedReader r = new BufferedReader(new InputStreamReader(in));
        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line).append('\n');
        }
        return total.toString();
    }

    // for simple testing
    private String buildJSONRequest(){
        JSONObject o = new JSONObject();
        try {
            o.put("name", "Sergey");
            o.put( "eyes", "grey");
            o.put( "hair", "grey");
            o.put( "cat", "Manul");
        }
        catch( JSONException e){
            Log.d("JSON", e.toString());
        }

        return o.toString();
    }

}
