package com.tomas.pcs_asi.lib.common;

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

import com.tomas.pcs_asi.R;

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

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);

    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("X-Requested-With","application/web-service");
            conn.setDoOutput(true);
            conn.setDoInput(true);

            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
//            os.writeBytes(URLEncoder.encode(json.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) {
            e.printStackTrace();
        }
        return null;
    }

}
