diff --git a/app/src/main/java/com/swoosh/microblog/data/repository/TagRepository.kt b/app/src/main/java/com/swoosh/microblog/data/repository/TagRepository.kt new file mode 100644 index 0000000..229e940 --- /dev/null +++ b/app/src/main/java/com/swoosh/microblog/data/repository/TagRepository.kt @@ -0,0 +1,86 @@ +package com.swoosh.microblog.data.repository + +import android.content.Context +import com.swoosh.microblog.data.AccountManager +import com.swoosh.microblog.data.api.ApiClient +import com.swoosh.microblog.data.api.GhostApiService +import com.swoosh.microblog.data.model.GhostTagFull +import com.swoosh.microblog.data.model.TagWrapper +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +class TagRepository(private val context: Context) { + + private val accountManager = AccountManager(context) + + private fun getApi(): GhostApiService { + val account = accountManager.getActiveAccount() + ?: throw IllegalStateException("No active account configured") + return ApiClient.getService(account.blogUrl) { account.apiKey } + } + + suspend fun fetchTags(): Result> = + withContext(Dispatchers.IO) { + try { + val response = getApi().getTags() + if (response.isSuccessful) { + Result.success(response.body()!!.tags) + } else { + Result.failure(Exception("API error ${response.code()}: ${response.errorBody()?.string()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun createTag( + name: String, + description: String? = null, + accentColor: String? = null + ): Result = + withContext(Dispatchers.IO) { + try { + val tag = GhostTagFull( + name = name, + description = description, + accent_color = accentColor + ) + val response = getApi().createTag(TagWrapper(listOf(tag))) + if (response.isSuccessful) { + Result.success(response.body()!!.tags.first()) + } else { + Result.failure(Exception("Create tag failed ${response.code()}: ${response.errorBody()?.string()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun updateTag(id: String, tag: GhostTagFull): Result = + withContext(Dispatchers.IO) { + try { + val response = getApi().updateTag(id, TagWrapper(listOf(tag))) + if (response.isSuccessful) { + Result.success(response.body()!!.tags.first()) + } else { + Result.failure(Exception("Update tag failed ${response.code()}: ${response.errorBody()?.string()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun deleteTag(id: String): Result = + withContext(Dispatchers.IO) { + try { + val response = getApi().deleteTag(id) + if (response.isSuccessful) { + Result.success(Unit) + } else { + Result.failure(Exception("Delete tag failed ${response.code()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } +}