package com.tomas.ht_mast.lib.common;

import android.content.Context;
import android.util.Log;
import com.tomas.ht_mast.R;

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

public abstract class HttpClient {

    Context context;
    String _url;
    String json;

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

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

    public String execute() {

        StringBuffer stringBuffer = new StringBuffer();

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

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

            String tmp;
            while ((tmp = br.readLine()) != null) {
                stringBuffer.append(tmp);
            }
            onFinished(stringBuffer.toString(), conn.getResponseCode());

            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return stringBuffer.toString();
    }

}
