orinfar 0.0.5

A Text Editor For Witches
use crate::mode::Mode;
use anyhow::{Result, bail};
use clap::Parser;
use std::{fs::OpenOptions, io::Write, path::PathBuf};

#[derive(Parser)]
#[clap(author, version, about, long_about = None)]
pub struct Cli {
    pub file_name: Option<String>,

    #[arg(short, long, value_enum, default_value_t = Mode::Normal)]
    pub mode: Mode,
    #[arg(short, long, default_value_t = true)]
    pub debug: bool,
}

impl Cli {
    pub fn parse_path() -> Result<(Self, Option<PathBuf>)> {
        let cli = Self::parse();

        match cli.file_name {
            Some(ref path) => {
                let path = PathBuf::from(path);

                if path.is_dir() {
                    // TODO netrw
                    bail!("Orinfar does not support directory navigation");
                } else if path.is_file() {
                    Ok((cli, Some(path)))
                } else {
                    std::fs::write(&path, "")?;

                    Ok((cli, Some(path)))
                }
            }
            None => Ok((cli, None)),
        }
    }
}

pub fn log_dir() -> PathBuf {
    let base = xdg::BaseDirectories::with_prefix("orinfar");
    base.get_state_home().expect("Could not find home")
}

pub fn log_file() -> PathBuf {
    log_dir().join("log")
}

pub fn data_file() -> PathBuf {
    log_dir().join("data")
}

pub fn log(contents: &impl ToString) {
    let mut file = OpenOptions::new()
        .append(true)
        .open(log_file())
        .expect("unable to open file");

    // append data to the file
    file.write_all(format!("{}\n", contents.to_string()).as_bytes())
        .expect("unable to append data");
}

pub fn write_data(key: &impl ToString, value: &impl ToString) {
    let mut file = OpenOptions::new()
        .append(true)
        .open(data_file())
        .expect("unable to open file");

    // append data to the file
    file.write_all(format!("{}:{}\n", key.to_string(), value.to_string()).as_bytes())
        .expect("unable to append data");
}

#[macro_export]
macro_rules! log {
    ($($arg:tt)*) => {
        if *DEBUG.get().unwrap() {
            $crate::io::log(&format!($($arg)*))
        }
    };
}