package es.verdnatura.domain

import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import com.google.gson.Gson
import com.google.gson.JsonObject
import es.verdnatura.MobileApplication
import es.verdnatura.R
import es.verdnatura.presentation.base.nameofFunction
import es.verdnatura.presentation.view.feature.login.activity.LoginActivity
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import kotlin.system.exitProcess

abstract class SalixCallback<T>(val context: Context) : Callback<T> {

    override fun onResponse(call: Call<T>, response: Response<T>) {
        if (response.isSuccessful) {
            onSuccess(response)
        } else {
            try {
                if (response.code() == 555) {
                    var message = JSONObject(response.message()).getString("Message")
                    onError(Error(message))
                } else if (response.code() == 401) {
                    if (!isActivityRunning(context, LoginActivity::class.java)) {
                        val intent = Intent(context, LoginActivity::class.java)
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
                        context.startActivity(intent)
                        exitProcess(0)
                    } else {
                        onError(Error(response.message().toString()))
                    }
                } else {

                    onError(Error(errorSalixMessage(response)))
                    //  onError(Error(response.message().toString()))
                }
            } catch (t: Throwable) {
                defaultErrorHandler(t)
            }
        }
    }

    override fun onFailure(call: Call<T>, t: Throwable) {
        try {
            onError(t)
        } catch (t: Throwable) {
            defaultErrorHandler(t)
        }
    }

    private fun defaultErrorHandler(t: Throwable) {
        //println("ErrorSalixx${t.message}")
        // (nameofFunction((this)) + t.message).toast(context)
        (context as MobileApplication).messageToast(true, (nameofFunction((this)) + t.message))
    }

    open fun onSuccess(response: Response<T>) {
        // (nameofFunction((this)) + context.getString(R.string.operationSuccessful)).toast(context)

        (context as MobileApplication).messageToast(
            isError = false,
            message = context.getString(R.string.operationSuccessful)
        )
    }

    open fun onError(t: Throwable) {
        throw t
    }

    fun isActivityRunning(context: Context, activityClass: Class<*>): Boolean {
        val packageName = context.packageName
        val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        val runningActivities = activityManager.getRunningTasks(Int.MAX_VALUE)

        for (taskInfo in runningActivities) {
            if (taskInfo.baseActivity?.className == activityClass.name && taskInfo.topActivity?.packageName == packageName) {
                return true
            }
        }

        return false
    }

    private fun errorSalixMessage(response: Response<T>): String {

        val messageResponse = response.errorBody()!!.string()
        return try {

            val jsonObject = Gson().fromJson(messageResponse, JsonObject::class.java)
            jsonObject?.getAsJsonObject("error")?.get("message")?.asString.toString()

        } catch (ex: Exception) {
            response.message()
        }

    }
}