package de.storchp.fdroidbuildstatus.adapter.gitlab

import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory
import de.storchp.fdroidbuildstatus.BuildConfig
import de.storchp.fdroidbuildstatus.adapter.ApiCallback
import de.storchp.fdroidbuildstatus.adapter.ApiResponse
import de.storchp.fdroidbuildstatus.utils.UserAgentInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.jackson.JacksonConverterFactory
import retrofit2.http.Path

private val TAG = GitlabClient::class.java.simpleName

class GitlabClient(baseUrl: String) {
    private val api: GitlabAPI

    init {
        val mapper = ObjectMapper(YAMLFactory())
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC)
        val builder: OkHttpClient.Builder = OkHttpClient.Builder()
            .addInterceptor(UserAgentInterceptor())
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(loggingInterceptor)
        }
        val retrofit = Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(builder.build())
            .addConverterFactory(JacksonConverterFactory.create(mapper))
            .build()
        api = retrofit.create(GitlabAPI::class.java)
    }

    fun getFdroidDataMetadata(@Path("id") id: String, callback: ApiCallback<Metadata?>) {
        val call = api.getFdroidDataMetadata(id)
        call!!.enqueue(object : Callback<Metadata?> {
            override fun onResponse(call: Call<Metadata?>, response: Response<Metadata?>) {
                Log.d(TAG, "loaded metadata versions for $id")
                val metadata = response.body()
                if (response.isSuccessful && metadata != null) {
                    callback.onResponse(ApiResponse.success(metadata))
                } else if (response.code() == 404 || metadata == null) {
                    callback.onResponse(
                        ApiResponse.error<Metadata?>(
                            ApiResponse.Status.NOT_FOUND,
                            response.message()
                        )
                    )
                } else {
                    Log.e(TAG, "error loading metadata for " + id + ": " + response.message())
                    callback.onResponse(ApiResponse.error<Metadata?>(response.message()))
                }
            }

            override fun onFailure(call: Call<Metadata?>, t: Throwable) {
                Log.e(TAG, "error loading metadata for $id", t)
                callback.onResponse(ApiResponse.error<Metadata?>(t.message))
            }
        })
    }

}