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.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

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

    Context context;
    String _url;
    String json = null;

    String filename;
    int resp_code = 200;

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

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

    public AsyncHttpClientFile(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(filename, 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","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();

            //Useful to display progress
            int fileLength = conn.getContentLength();


            //Download the file
            InputStream input = new BufferedInputStream(conn.getInputStream());
            File dir = new File(context.getFilesDir(), "/temp");
            dir.mkdir();
            File file = new File(dir, "temp.pdf");
            OutputStream output = new FileOutputStream(file);

            byte[] data = new byte[1024];
            long total = 0;
            int count;
            while ((count = input.read(data)) != -1) {
                if(isCancelled()) {
                    input.close();
                    return null;
                }
                total += count;


                output.write(data);

            }


            output.flush();
            output.close();
            input.close();

            filename = context.getFilesDir() + "/temp/temp.pdf";
            resp_code = conn.getResponseCode();

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

}
