package com.dbs.mplus.knuh.httpTask;

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

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class HttpImageUpload extends AsyncTask<Void, Void, Boolean> {
  private String CRLF       = "\r\n";
  private String twoHyphens = "--";
  private String boundary   = "";
  private String url        = "";
  private File uploadFile   = null;
  private String fileName   = "";
  private DataOutputStream dataStream = null;

  public HttpImageUpload(String url, File uploadFile, String fileName) {
    this.url        = url;
    this.uploadFile = uploadFile;
    this.fileName   = fileName;
    this.boundary   = "**" + Long.toHexString(System.currentTimeMillis());
  }

  @Override
  protected Boolean doInBackground(Void... voids) {
    boolean result = false;
    if (uploadFile.exists() == false) {
      return false;
    }
    try {
      FileInputStream fileInputStream = new FileInputStream(uploadFile);
      URL connectURL = new URL(url);
      HttpURLConnection conn = (HttpURLConnection) connectURL.openConnection();

      conn.setDoInput(true);
      conn.setDoOutput(true);
      conn.setUseCaches(false);
      conn.setRequestMethod("POST");

      //conn.setRequestProperty("User-Agent", "myGeodiary-V1");
      conn.setRequestProperty("Connection", "Keep-Alive");
      conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
      conn.connect();

      dataStream = new DataOutputStream(conn.getOutputStream());

//      if (!fileType.equals("image/jpg")) {
//      }

      String fileType = URLConnection.guessContentTypeFromName(fileName);
      writeFileField("up_path", fileName, fileType, fileInputStream);

      // final closing boundary line
      dataStream.writeBytes(twoHyphens + boundary + twoHyphens + CRLF);

      fileInputStream.close();
      dataStream.flush();
      if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
        result = true;
      }
    } catch (Exception e) {
      Log.i("Exception info: ", e.toString());
      e.printStackTrace();
    } finally {
      if (dataStream != null) {
        try {
          dataStream.close();
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      dataStream = null;
    }
    return result;
  }


  /**
   * write one file field to dataSream
   * @param fieldName - name of file field
   * @param fieldValue - file name
   * @param type - mime type
   * @param fis - stream of bytes that get sent up
   */
  private void writeFileField(String fieldName, String fieldValue, String type, FileInputStream fis) {
    try {
//      Log.e("writeFileField", "fieldName : "+ fieldName);
//      Log.e("writeFileField", "fieldValue : "+ fieldValue);
//      Log.e("writeFileField", "type : "+ type);
      // opening boundary line
      dataStream.writeBytes(twoHyphens + boundary + CRLF);
      dataStream.writeBytes("Content-Disposition: form-data; name=\""
          + fieldName
          + "\";filename=\""
          + fieldValue
          + "\""
          + CRLF);
      dataStream.writeBytes("Content-Type: " + type +  CRLF);
      dataStream.writeBytes(CRLF);

      // create a buffer of maximum size
      int bytesAvailable = fis.available();
      int maxBufferSize = 1024;
      int bufferSize = Math.min(bytesAvailable, maxBufferSize);
      byte[] buffer = new byte[bufferSize];
      // read file and write it into form...
      int bytesRead = fis.read(buffer, 0, bufferSize);
      while (bytesRead > 0) {
        dataStream.write(buffer, 0, bufferSize);
        bytesAvailable = fis.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fis.read(buffer, 0, bufferSize);
      }

      // closing CRLF
      dataStream.writeBytes(CRLF);
    } catch(Exception e) {
      e.printStackTrace();
    }
  }
}
