use ratatui::widgets::ListState;
use sqlite::Connection;

use crate::{data_layer, entities::*};

pub struct AccountList {
    accounts: Vec<Account>,
    pub state: ListState,
}
impl AccountList {
    pub fn new() -> AccountList {
        let mut list_state = ListState::default();
        list_state.select_first();
        return AccountList {
            accounts: Vec::new(),
            state: list_state,
        };
    }

    pub fn get_accounts(
        &mut self,
        con: &Connection,
    ) -> Result<Vec<Account>, Box<dyn std::error::Error>> {
        if self.accounts.iter().count() == 0 {
            self.accounts = data_layer::get_accounts(con)?;
        }
        return Ok(self.accounts.clone());
    }

    pub fn get_selected_id(&self) -> i64 {
        if let Some(i) = self.state.selected() {
            self.accounts.get(i).map(|a| a.get_id()).unwrap_or(-1)
        } else {
            -1
        }
    }

    pub fn selected_ac(&self) -> Account {
        if let Some(i) = self.state.selected() {
            match self.accounts.get(i) {
                Some(a) => return a.clone(),
                None => return Account::new_empty(),
            }
        }
        return Account::new_empty();
    }

    pub fn add_account(&mut self, ac: Account) {
        self.accounts.push(ac);
    }
}