use camino::Utf8PathBuf;
use jiff::Timestamp;
use libpijul::pristine::InodeMetadata;
use libpijul::working_copy::WorkingCopyRead;
use ropey::Rope;

#[derive(Clone, Debug)]
pub struct FileContents {
    pub metadata: InodeMetadata,
    pub modified_time: Timestamp,
    pub text: Rope,
}

impl FileContents {
    pub fn new<W: WorkingCopyRead>(
        path: Utf8PathBuf,
        metadata: InodeMetadata,
        contents: String,
        working_copy: &W,
    ) -> Self {
        let last_modified_time = match working_copy.modified_time(path.as_str()) {
            Ok(modified_time) => match Timestamp::try_from(modified_time) {
                Ok(converted_timestamp) => converted_timestamp,
                Err(error) => {
                    tracing::error!(
                        message = "jiff::Timestamp::TryFrom<std::time::SystemTime> failed",
                        ?error
                    );

                    Timestamp::now()
                }
            },
            Err(error) => {
                tracing::error!(
                    message = "Failed to get modified time from working copy",
                    ?error
                );

                Timestamp::now()
            }
        };

        Self {
            metadata,
            modified_time: last_modified_time,
            text: Rope::from(contents),
        }
    }
}