package org.wntr.mdeditor

import android.content.Context
import android.util.Log
import android.widget.Toast
import com.franmontiel.persistentcookiejar.ClearableCookieJar
import com.franmontiel.persistentcookiejar.PersistentCookieJar
import com.franmontiel.persistentcookiejar.cache.SetCookieCache
import com.franmontiel.persistentcookiejar.persistence.SharedPrefsCookiePersistor
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.ResponseBody
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import retrofit2.http.Body
import retrofit2.http.DELETE
import retrofit2.http.GET
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.PUT
import retrofit2.http.Part
import retrofit2.http.Path

object RetrofitClient {
    fun getClient(applicationContext: Context, baseUrl: String): Retrofit {
        /* Detailed logging
        val loggingInterceptor = HttpLoggingInterceptor().apply {
        this.setLevel(HttpLoggingInterceptor.Level.BASIC)
        }*/
        Log.i(javaClass.simpleName, "Retrofitclient baseurl: $baseUrl")
        for (cookie in SharedPrefsCookiePersistor(applicationContext).loadAll()) {
            Log.d(javaClass.simpleName, "cookie for: ${cookie.domain}")
        }
        val cookieJar: ClearableCookieJar =
            PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(applicationContext))

        val okHttpClient = OkHttpClient()
            .newBuilder()
            /*
            .addInterceptor(RequestInterceptor)
            */
            /*
            .addInterceptor(loggingInterceptor)
            */
            .cookieJar(cookieJar)
            .build()

        return Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(baseUrl + "/ghost/api/admin/")
            .addConverterFactory(JacksonConverterFactory.create())
            .build()
    }
}

class ghostAPI(applicationContext: Context, instance: String) {
    val retrofit = RetrofitClient.getClient(applicationContext, instance)
    val postApi = retrofit.create(PostApi::class.java)
    val baseUrl = instance


    fun register(credentials: Credentials): String {
        return try {
            val response = postApi.getCookie(credentials).execute()
            if (!response.isSuccessful) {
                Log.d(javaClass.simpleName, "Response code ${response.code()}")
                when (response.code()) {
                    401 -> {
                        return "404"
                    }
                    404 -> {
                        return "404"
                    }

                    429 -> {
                        Log.d(javaClass.simpleName, "Too many failures")
                        return "TOO_MANY_FAILURES"
                    }

                    else -> {
                        val errors = JSONObject(response.errorBody()!!.string())
                        val code =
                            errors.getJSONArray("errors").getJSONObject(0).getString("code")
                        Log.d(javaClass.simpleName, "Error code $code")
                        if (code.equals("PASSWORD_INCORRECT")) {
                            Log.d(javaClass.simpleName, "Password incorrect")

                        }
                        if (code !== null) return code
                        else return response.code().toString()
                    }
                }
            }
            return "SUCCESS"
        } catch (ex: Exception) {
            Log.d(javaClass.simpleName, "Couldn't log in. Exception: ${ex}")
            return "EXCEPTION"
        }
    }



    /* Detailed logging

    object RequestInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newRequest = request.newBuilder()
            *//*.header("Authorization", "Ghost "+ API_KEY)*//*
                .header("Origin", "https://mary.joefix.it")

                .build()

            Log.i(javaClass.simpleName, "Outgoing request to ${newRequest.url}")
            //Log.i(javaClass.simpleName, newRequest.body.toString())
            return chain.proceed(newRequest)
        }
    }
    */
}

interface PostApi {
    @GET("posts/")
    fun getPosts(): Call<ResponseBody>
    /*  fun getPosts(): Call<ResponseBody>  <- for json string*/

    @DELETE("posts/{id}")
    fun deletePost(@Path("id") id: String): Call<ResponseBody>

    @POST("session")
    fun getCookie(@Body credentials: Credentials): Call<ResponseBody>

    @POST("posts/?source=html")
    fun pushPost(@Body postings: sendPostList): Call<ResponseBody>

    @PUT("posts/{id}?source=html")
    fun updatePost(@Path("id") id: String, @Body postings:sendPostList): Call<ResponseBody>

    @Multipart
    @POST("images/upload")
    fun pushMyImage(@Part file: MultipartBody.Part): Call<imagesObj>
}

