use crate::*;

#[uniffi::export(async_runtime = "tokio")]
impl GotchaCore {
    pub async fn repositories(
        &self,
        page: u32,
        pane: RepositoryPane,
    ) -> Result<RepositoryListPage, GotchaError> {
        let server = self.server()?;
        let page_number = valid_page(page)?;
        let repositories = load_repositories(&server, page_number).await?;
        let mut state = self.state.lock().unwrap();
        if page_number == 1 {
            state.repositories.clear();
        }
        for repository in repositories.items {
            if let Some(existing) = state.repositories.iter_mut().find(|candidate| {
                candidate.owner == repository.owner && candidate.name == repository.name
            }) {
                *existing = repository;
            } else {
                state.repositories.push(repository);
            }
        }
        Ok(RepositoryListPage {
            rows: self.repository_rows(&state, pane),
            has_more: repositories.has_more,
        })
    }

    pub fn toggle_favorite(
        &self,
        owner: String,
        repository: String,
        pane: RepositoryPane,
    ) -> Result<Vec<RepositoryRow>, GotchaError> {
        let mut state = self.state.lock().unwrap();
        let server = state
            .active_server
            .and_then(|index| state.preferences.servers.get(index))
            .ok_or("Select a server first.")?;
        let key = favorite_key(pane, &server.url, &owner, &repository);
        if !state.preferences.favorites.remove(&key) {
            state.preferences.favorites.insert(key);
        }
        save_preferences(&state.preferences)?;
        Ok(self.repository_rows(&state, pane))
    }
}
