package it.danieleverducci.openweddingapp.networking

import android.os.AsyncTask
import android.util.Log
import it.danieleverducci.openweddingapp.Config
import it.danieleverducci.openweddingapp.entities.GalleryItem
import it.danieleverducci.openweddingapp.utils.ImageUtils
import org.json.JSONObject
import java.io.File
import java.io.IOException

class UploadItemAsyncTask(val token: String, val listener: GalleryItemNet.OnGalleryItemUploadCompletedListener): AsyncTask<File, Void, JSONObject?>() {
    companion object {
        val TAG = "UploadItemAsyncTask"
    }


    override fun doInBackground(vararg p0: File?): JSONObject? {
        if (p0.size == 0 || p0[0] == null) {
            Log.e(TAG, "No image file received")
            return JSONObject()
        }

        val file = p0[0]!!

        // Resize image to meet maximum upload size
        if (file.length() >= Config.MAX_UPLOAD_IMAGE_SIZE)
            ImageUtils.resizeImage(file)


        // Send image to server
        val multipart =
            AuthenticatedMultipartRequest(
                token,
                "${Config.API_BASE_URL}${Config.API_ENDPOINT_GALLERY_ITEM}/upload.php",
                "UTF-8"
            )
        multipart.addFilePart("image", file)

        try {
            val response = multipart.finish()
            for (line in response) {
                return JSONObject(line)
            }
            return JSONObject("{}")
        } catch (e: IOException) {
            Log.e(TAG, "Unable to send image to server: " + e.toString())
            return null
        }
    }

    override fun onPostExecute(result: JSONObject?) {
        super.onPostExecute(result)

        if (result != null && result.has("success")) {
            val itemJson = result.optJSONObject("record")
            var galleryItem: GalleryItem? = null
            if (itemJson != null)
                galleryItem = GalleryItem(itemJson)
            listener.OnGalleryItemUploaded(galleryItem, result.getString("errorMessage"))
        } else {
            listener.OnGalleryItemUploaded(null, "Server error")
        }
    }

}