package com.tomastc.smartwatchclient.lib.common;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;

import com.tomastc.smartwatchclient.R;

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

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

    Context context;
    String _url;
    String json = null;

    Bitmap bitmap;
    int resp_code = 200;

    abstract protected void onFinished(Bitmap bitmap, int resp_code);

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

    public AsyncHttpClientImage(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(bitmap, resp_code);
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Log.d(context.getString(R.string.tag), "url: " + _url);
        if (json != null && !json.isEmpty())
            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",
                    json == null || json.isEmpty() ? "application/x-www-form-urlencoded;charset=UTF-8" : "application/json");
            conn.setRequestProperty("Accept","image/png;image/jpeg;image/jpg");
            conn.addRequestProperty("User-Agent", context.getString(R.string.user_agent));
            conn.addRequestProperty("X-Requested-With",context.getString(R.string.x_requested_with));
            conn.setDoOutput(true);
            conn.setDoInput(true);

            DataOutputStream os = new DataOutputStream(conn.getOutputStream());
            //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
            if (json != null && !json.isEmpty()) {
                os.writeBytes(json);
            }

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

            //BufferedReader br = null;
            Log.d(context.getString(R.string.tag), "response code: " + conn.getResponseCode());
            if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399
              || conn.getResponseCode() == 405) {
                bitmap = BitmapFactory.decodeStream(conn.getInputStream());
            }
            resp_code = conn.getResponseCode();

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

}
