package com.tomastc.smartwatchclient.lib.common;

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

import com.tomastc.smartwatchclient.R;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public abstract class AsyncHttpClientInputStream extends AsyncTask<String,Void, InputStream> {

    Context context;
    String _url;
    String json = null;

    InputStream inputStream;
    int resp_code = 200;

    abstract protected void onFinished(InputStream inputStream, int resp_code);

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

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

    @Override
    protected void onPostExecute(InputStream inputStream) {
        // after the execution of our async
        // task we are loading our pdf in our pdf view.
        onFinished(inputStream, resp_code);
        //pdfView.fromStream(inputStream).load();
    }

    @Override
    protected InputStream doInBackground(String... strings) {
        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","application/pdf");
            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();


            inputStream = new BufferedInputStream(conn.getInputStream());
            resp_code = conn.getResponseCode();

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

}
