package com.xypower.common;

import android.text.TextUtils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.util.UUID;

public class FileUploader {

    private HttpURLConnection httpConn;
    private DataOutputStream request;
    private final static String BOUNDARY =  UUID.randomUUID().toString();;
    private final static String CRLF = "\r\n";
    private final static String twoHyphens = "--";

    /**
     * This constructor initializes a new HTTP POST request with content type
     * is set to multipart/form-data
     *
     * @param requestURL
     * @throws IOException
     */
    public FileUploader(String requestURL)
            throws IOException {

        // creates a unique boundary based on time stamp
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);

        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        httpConn.setRequestProperty("Cache-Control", "no-cache");
        httpConn.setRequestProperty(
                "Content-Type", "multipart/form-data;boundary=" + this.BOUNDARY);

        request =  new DataOutputStream(httpConn.getOutputStream());
    }

    @Override
    protected void finalize() {
        if (httpConn != null) {
            try {
                httpConn.disconnect();
            } catch (Exception ex) {

            }
        }
    }

    /**
     * Adds a form field to the request
     *
     * @param name  field name
     * @param value field value
     */
    public void addFormField(String name, String value) throws IOException  {
        request.writeBytes(this.twoHyphens + this.BOUNDARY + this.CRLF);
        request.writeBytes("Content-Disposition: form-data; name=\"" + name + "\""+ this.CRLF);
        request.writeBytes("Content-Type: text/plain; charset=UTF-8" + this.CRLF);
        request.writeBytes(this.CRLF);
        request.writeBytes(value+ this.CRLF);
        request.flush();
    }

    /**
     * Adds a upload file section to the request
     *
     * @param fieldName  name attribute in <input type="file" name="..." />
     * @param uploadFile a File to be uploaded
     * @throws IOException
     */
    public void addFilePart(String fieldName, File uploadFile, String fileName, String mimeType)
            throws IOException {
        request.writeBytes(this.twoHyphens + this.BOUNDARY + this.CRLF);
        request.writeBytes("Content-Disposition: form-data; name=\"" +
                fieldName + "\";filename=\"" +
                (TextUtils.isEmpty(fileName) ? uploadFile.getName() : fileName) + "\"" + this.CRLF);
        if (!TextUtils.isEmpty(mimeType)) {
            request.writeBytes("Content-Type: " + mimeType + "; charset=" + "UTF-8" + this.CRLF);
        }
        request.writeBytes(this.CRLF);

        byte[] bytes = Files.readAllBytes(uploadFile.toPath());
        request.write(bytes);
    }

    /**
     * Completes the request and receives response from the server.
     *
     * @return a list of Strings as response in case the server returned
     * status OK, otherwise an exception is thrown.
     * @throws IOException
     */
    public String finish() throws IOException {
        String response ="";

        request.writeBytes(this.CRLF);
        request.writeBytes(this.twoHyphens + this.BOUNDARY +
                this.twoHyphens + this.CRLF);

        request.flush();
        request.close();

        // checks server's status code first
        int status = httpConn.getResponseCode();
        if (status == HttpURLConnection.HTTP_OK) {
            InputStream responseStream = new
                    BufferedInputStream(httpConn.getInputStream());

            BufferedReader responseStreamReader =
                    new BufferedReader(new InputStreamReader(responseStream));

            String line = "";
            StringBuilder stringBuilder = new StringBuilder();

            while ((line = responseStreamReader.readLine()) != null) {
                stringBuilder.append(line).append("\n");
            }
            responseStreamReader.close();

            response = stringBuilder.toString();
            httpConn.disconnect();
            httpConn = null;
        } else {
            throw new IOException("Server returned non-OK status: " + status);
        }

        return response;
    }
}
