package com.seatel.mobilehall.ui.profile.presenter

import android.content.Context
import com.android.volley.Request
import com.google.gson.Gson
import com.seatel.mobilehall.data.network.SeatelJSONObjectRequest
import com.seatel.mobilehall.ui.login.model.UploadImageResponse
import com.seatel.mobilehall.ui.profile.interactor.UploadImageInteractor
import com.seatel.mobilehall.util.Constant
import com.seatel.mobilehall.util.MultipartEntityRequest
import org.json.JSONObject
import java.io.File

class UploadImagePresenter(private var context: Context) : UploadImageInteractor.Presenter {

    private var mView = context as UploadImageInteractor.View

    override fun onUpdate(phoneNum: String, fileName: String) {

        getUpdateRequest(phoneNum, fileName).setOnErrorListener { error ->
            mView.onUploadFailed(
                error
            )
        }.setOnResponseListener { mView.onUpdateSucceed() }.execute()
    }

    private fun getUpdateRequest(
        phoneNum: String,
        imageName: String
    ): SeatelJSONObjectRequest {


        return object : SeatelJSONObjectRequest(context) {

            override fun getFunctionName(): String {
                return "seatel/$phoneNum/profile"
            }


            override fun onGetBodyRequest(): String {
                val json = JSONObject()
                json.put("profilePicture", imageName)
                return json.toString()
            }

            override fun getMethod(): Int {
                return Request.Method.PUT
            }


        }
    }

    override fun onUpload(file: File) {

        val multi =
            MultipartEntityRequest.with(context)
                .setType(Constant.ANY).setFile(file)
        multi.setOnErrorListener { error ->
            mView.onUploadFailed(error)
        }


        multi.upLoadImage { response ->
            mView.onUploadSucceed(getUploadResponseModel(response))
        }
    }

    private fun getUploadResponseModel(data: String): UploadImageResponse {
        return Gson().fromJson(data, UploadImageResponse::class.java)
    }

//    private fun getImageModel(obj : JSONObject) : UploadImageResponse{
//
//        val imageModels = UploadImageResponse()
//        val data = obj.("data",)
//        val imageLength = data.length()
//        val imageModelList = ArrayList<ImageUploadModel>()
//
//        for (i in 0..imageLength){
//
//            val imageModel = ImageUploadModel()
//
//            imageModel.fieldname = data.optJSONObject(i).optString("filename")
//            imageModel.path = data.optJSONObject(i).optString("path")
//            imageModelList.add(imageModel)
//        }
//
//        imageModels.data = imageModelList
//        return imageModels
//    }

}