// Copyright (C) 2022-2023 Enrico Guiraud
//
// This file is part of Kobold, a static site generator with a friendly CLI.
//
// Kobold is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Kobold is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Kobold. If not, see <http://www.gnu.org/licenses/>.

use std::borrow::Cow;
use std::path::Path;
use walkdir::WalkDir;

type Result<T> = std::result::Result<T, Cow<'static, str>>;

pub fn copy_dir_contents(from_dir: &Path, to_dir: &Path) -> Result<()> {
    for entry in WalkDir::new(from_dir) {
        let entry = entry.map_err(|msg| {
            format!(
                "There was an error while copying contents of directory {}:\n\t{}",
                from_dir.display(),
                msg
            )
        })?;

        if entry
            .metadata()
            .map_err(|msg| {
                format!(
                    "There was an error while accessing metadata of path {}:\n\t{}",
                    entry.path().display(),
                    msg
                )
            })?
            .is_file()
        {
            let output_path = entry.path().strip_prefix(from_dir).unwrap();
            let output_path = to_dir.join(output_path);
            copy_file(entry.path(), &output_path)?;
        }
    }

    Ok(())
}

pub fn copy_file(from: &Path, to: &Path) -> Result<()> {
    std::fs::copy(from, to).map_err(|msg| {
        format!(
            "There was an error while copying file {} to {}:\n\t{}",
            from.display(),
            to.display(),
            msg
        )
    })?;

    Ok(())
}

pub fn create_dir(output_dir: &Path) -> Result<()> {
    std::fs::create_dir_all(output_dir).map_err(|msg| {
        Cow::from(format!(
            "Could not create directory '{}':\n\t{}",
            output_dir.display(),
            msg
        ))
    })?;
    Ok(())
}
