diff --git a/app/src/main/java/com/swoosh/microblog/data/repository/PageRepository.kt b/app/src/main/java/com/swoosh/microblog/data/repository/PageRepository.kt new file mode 100644 index 0000000..5fa6d50 --- /dev/null +++ b/app/src/main/java/com/swoosh/microblog/data/repository/PageRepository.kt @@ -0,0 +1,81 @@ +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.GhostPage +import com.swoosh.microblog.data.model.PageWrapper +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext + +class PageRepository(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 } + } + + fun getBlogUrl(): String? { + return accountManager.getActiveAccount()?.blogUrl + } + + suspend fun fetchPages(): Result> = + withContext(Dispatchers.IO) { + try { + val response = getApi().getPages() + if (response.isSuccessful) { + Result.success(response.body()!!.pages) + } else { + Result.failure(Exception("API error ${response.code()}: ${response.errorBody()?.string()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun createPage(page: GhostPage): Result = + withContext(Dispatchers.IO) { + try { + val response = getApi().createPage(PageWrapper(listOf(page))) + if (response.isSuccessful) { + Result.success(response.body()!!.pages.first()) + } else { + Result.failure(Exception("Create failed ${response.code()}: ${response.errorBody()?.string()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun updatePage(id: String, page: GhostPage): Result = + withContext(Dispatchers.IO) { + try { + val response = getApi().updatePage(id, PageWrapper(listOf(page))) + if (response.isSuccessful) { + Result.success(response.body()!!.pages.first()) + } else { + Result.failure(Exception("Update failed ${response.code()}: ${response.errorBody()?.string()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun deletePage(id: String): Result = + withContext(Dispatchers.IO) { + try { + val response = getApi().deletePage(id) + if (response.isSuccessful) { + Result.success(Unit) + } else { + Result.failure(Exception("Delete failed ${response.code()}")) + } + } catch (e: Exception) { + Result.failure(e) + } + } +}