From 7baaeab05f82b80aa7005cdb6074f72eee6bd8cd Mon Sep 17 00:00:00 2001
From: ducdetronquito <g.paulet@smartway.ai>
Date: Sat, 23 Dec 2023 12:51:03 +0100
Subject: [PATCH] feat: Can add a birthday and show all birthdays

---
 src/lib.rs  | 45 +++++++++++++++++++++++++++++++++++++++++++++
 src/main.rs | 21 ++++++++++++++++++---
 2 files changed, 63 insertions(+), 3 deletions(-)
 create mode 100644 src/lib.rs

diff --git a/src/lib.rs b/src/lib.rs
new file mode 100644
index 0000000..c443104
--- /dev/null
+++ b/src/lib.rs
@@ -0,0 +1,45 @@
+use anyhow::Result;
+use chrono::NaiveDate;
+use rusqlite::Connection;
+
+fn get_db() -> Result<Connection> {
+    let db = Connection::open("test.db")?;
+    db.execute(
+        "CREATE TABLE IF NOT EXISTS birthdays (
+             id INTEGER PRIMARY KEY,
+             name TEXT NOT NULL,
+             date TEXT NOT NULL
+         ) STRICT",
+        (),
+    )?;
+    Ok(db)
+}
+
+pub fn add_birthday(name: String, date: String) -> Result<()> {
+    let db = get_db()?;
+    let naive_date = NaiveDate::parse_from_str(&date, "%Y-%m-%d")?;
+    db.execute(
+        "INSERT INTO birthdays(name, date) VALUES(?1, ?2)",
+        (name, naive_date),
+    )?;
+    Ok(())
+}
+
+#[derive(Debug)]
+pub struct Birthday {
+    name: String,
+    date: NaiveDate,
+}
+
+pub fn show_all_birthdays() -> Result<Vec<Birthday>> {
+    let db = get_db()?;
+    let mut statement = db.prepare("SELECT name, date FROM birthdays")?;
+    let birthday_iter = statement.query_map([], |row| {
+        Ok(Birthday {
+            name: row.get(0)?,
+            date: row.get(1)?,
+        })
+    })?;
+    let birthdays: Result<Vec<Birthday>, rusqlite::Error> = birthday_iter.collect();
+    Ok(birthdays.unwrap())
+}
diff --git a/src/main.rs b/src/main.rs
index e507af7..1820fec 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,3 +1,5 @@
+use anyhow::Result;
+use birthday::add_birthday;
 use clap::{Parser, Subcommand};
 
 #[derive(Parser, Debug)]
@@ -29,7 +31,20 @@ enum Command {
     Today {},
 }
 
-fn main() {
-    let args = Cli::parse();
-    println!("You ran cli with: {:?}", args);
+fn main() -> Result<()> {
+    let cli = Cli::parse();
+    println!("You ran cli with: {:?}", cli);
+    match cli.command {
+        Command::Add { name, date } => birthday::add_birthday(name, date),
+        Command::All {} => {
+            let birthdays = birthday::show_all_birthdays()?;
+            for birthday in birthdays {
+                println!("{:?}", birthday);
+            }
+            Ok(())
+        }
+        Command::Next {} => todo!(),
+        Command::Search { name, date } => todo!(),
+        Command::Today {} => todo!(),
+    }
 }