use std::io::{self, BufRead};
use crate::{
config::Config,
error::Result,
habitica::{HabiticaClient, StatsCache},
sync::{converter, ConflictResolver},
taskwarrior::{NotesManager, Task, TaskwarriorClient},
};
pub fn handle_modify(config: &Config) -> Result<()> {
let stdin = io::stdin();
let mut lines = stdin.lock().lines();
let old_task_json = lines
.next()
.ok_or_else(|| crate::error::Error::custom("No old task provided"))??;
let new_task_json = lines
.next()
.ok_or_else(|| crate::error::Error::custom("No new task provided"))??;
let old_task: Task = serde_json::from_str(&old_task_json)?;
let new_task: Task = serde_json::from_str(&new_task_json)?;
let notes_manager = NotesManager::new(config);
let note_recently_changed = notes_manager.note_recently_modified(&new_task)?;
let old_note_annos = old_task.filter_note_annotations(&config.task_note_prefix);
let new_note_annos = new_task.filter_note_annotations(&config.task_note_prefix);
let note_content = notes_manager.read_note(&new_task)?;
let old_h_opt = converter::taskwarrior_to_habitica(&old_task, note_content.as_deref())?;
let new_h_opt = converter::taskwarrior_to_habitica(&new_task, note_content.as_deref())?;
if old_h_opt == new_h_opt && !note_recently_changed && old_note_annos == new_note_annos {
let output_json = serde_json::to_string(&new_task)?;
println!("{}", output_json);
return Ok(());
}
let tw_client = TaskwarriorClient::new();
let h_client = HabiticaClient::new(config)?;
let resolver = ConflictResolver::new(config, &tw_client, &h_client);
let mut stats_cache = StatsCache::load(&config.stats_cache_path())?
.or_else(|| h_client.get_user_stats().ok().map(StatsCache::new));
let updated_task = resolver.modify_on_habitica(&old_task, &new_task, &mut stats_cache)?;
if let Some(cache) = &stats_cache {
cache.save(&config.stats_cache_path())?;
}
let output_json = serde_json::to_string(&updated_task)?;
println!("{}", output_json);
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn test_modify_command_exists() {}
}