package com.tomastc.bta500.lib.common;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.tomastc.bta500.R;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public abstract class AsyncHttpClient extends AsyncTask<Void,Void,Void> {

    Context context;
    String _url;
    String json;

    StringBuffer stringBuffer = new StringBuffer();
    int resp_code = 200;

    abstract protected void onFinished(String response, int resp_code);
    abstract protected void onError(Exception e);

    public AsyncHttpClient(Context context, String url, String json) {
        this.context = context;
        this._url = url;
        this.json = json;
    }

    @Override
    protected void onPostExecute(Void unused) {
        super.onPostExecute(unused);
        onFinished(stringBuffer.toString(), resp_code);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Log.d(context.getString(R.string.tag), "url: " + _url);
        Log.d(context.getString(R.string.tag), "JSON post: " + json);

        try {
            URL url = new URL(_url);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
            conn.setRequestProperty("Accept","application/json");
            conn.addRequestProperty("User-Agent","use-for-webservice-only");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
            os.writeBytes(json);

            os.flush();
            os.close();

            BufferedReader br = null;
            if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            } else {
                br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }

            resp_code = conn.getResponseCode();
            Log.i(context.getString(R.string.tag),
                    String.format("%d(%s)", resp_code, conn.getResponseMessage()));

            String tmp;
            while ((tmp = br.readLine()) != null) {
                stringBuffer.append(tmp);
                stringBuffer.append("\r\n");
            }

            conn.disconnect();
        } catch (Exception e) {
            onError(e);
        }
        return null;
    }

}
