// License: see LICENSE file at root directory of `master` branch

//! # Root

use std::{
    fs::{self, File, ReadDir},
    io::{self, BufReader, Error, ErrorKind, Read},
    path::{Path, PathBuf},
};

use crate::filter;

/// # File discovery
///
/// ## Notes
///
/// - You can make this struct by [`::find_files()`][::find_files()].
/// - If sub directories are symlinks, they will be ignored.
///
/// [::find_files()]: fn.find_files.html
#[derive(Debug)]
pub struct FileDiscovery<F> where F: filter::Filter {

    /// # Filter
    filter: F,

    /// # Recursive
    recursive: bool,

    /// # Current
    current: ReadDir,

    /// # Sub directories
    sub_dirs: Option<Vec<PathBuf>>,

}

impl<F> Iterator for FileDiscovery<F> where F: filter::Filter {

    type Item = io::Result<PathBuf>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            match self.current.next() {
                Some(entry) => match entry {
                    Ok(entry) => match entry.file_type() {
                        Ok(file_type) => {
                            let path = entry.path();
                            let is_symlink = file_type.is_symlink();
                            if file_type.is_dir() || (is_symlink && path.is_dir()) {
                                if self.recursive == false || is_symlink {
                                    continue;
                                }

                                if self.filter.accept(&path) == false {
                                    continue;
                                }

                                match self.sub_dirs.as_mut() {
                                    Some(sub_dirs) => sub_dirs.push(path),
                                    None => self.sub_dirs = Some(vec![path]),
                                };
                            } else if file_type.is_file() || (is_symlink && path.is_file()) {
                                if self.filter.accept(&path) == false {
                                    continue;
                                }
                                return Some(Ok(path));
                            }
                        },
                        Err(err) => return Some(Err(err)),
                    },
                    Err(err) => return Some(Err(err)),
                },
                None => match self.sub_dirs.as_mut() {
                    None => return None,
                    Some(sub_dirs) => match sub_dirs.len() {
                        0 => return None,
                        _ => match fs::read_dir(sub_dirs.remove(0)) {
                            Ok(new) => self.current = new,
                            Err(err) => return Some(Err(err)),
                        },
                    },
                },
            };
        }
    }

}

/// # Finds files
///
/// This function makes new instance of [`FileDiscovery`][::FileDiscovery]. You should refer to that struct for notes on usage.
///
/// [::FileDiscovery]: struct.FileDiscovery.html
pub fn find_files<P, F>(dir: P, recursive: bool, filter: F) -> io::Result<FileDiscovery<F>> where P: AsRef<Path>, F: filter::Filter {
    Ok(FileDiscovery {
        filter,
        recursive,
        current: fs::read_dir(dir)?,
        sub_dirs: None,
    })
}

/// # Reads bytes from a source
///
/// ## Notes
///
/// - If data to be read exceeds limit, an error is returned. If you don't care about exceeding data, you can use
///   [`Read::take()`][rust::Read::take()].
/// - Source will be used as-is, without any wrapper. So you might want to use [`BufReader`][rust::BufReader].
///
/// ## Errors
///
/// While reading from source, if any error raises, it will be returned.
///
/// ## Examples
///
/// ```
/// use std::{
///     fs::File,
///     io::{self, BufReader},
///     path::PathBuf,
/// };
///
/// fn test() -> io::Result<()> {
///     let f = file!();
///     let file_size = PathBuf::from(f).metadata()?.len();
///
///     assert_eq!(
///         dia_files::read(&mut BufReader::new(File::open(f)?), None)?.len(),
///         dia_files::read(&mut BufReader::new(File::open(f)?), Some(file_size as usize))?.len(),
///     );
///
///     dia_files::read(&mut BufReader::new(File::open(f)?), Some(0)).unwrap_err();
///
///     Ok(())
/// }
///
/// test().unwrap();
/// ```
///
/// [rust::Read::take()]: https://doc.rust-lang.org/std/io/trait.Read.html#method.take
/// [rust::BufReader]: https://doc.rust-lang.org/std/io/struct.BufReader.html
pub fn read(src: &mut Read, limit: Option<usize>) -> io::Result<Vec<u8>> {
    let mut buf = [0; 8 * 1024];
    let mut result = vec![];
    loop {
        match src.read(&mut buf)? {
            0 => return Ok(result),
            read => {
                if let Some(limit) = limit {
                    match result.len().checked_add(read) {
                        Some(new_len) => if new_len > limit {
                            return Err(Error::new(ErrorKind::Other, "Data exceeds limit"));
                        },
                        None => return Err(Error::new(ErrorKind::Other, "Too much data to read")),
                    };
                }

                result.extend(&buf[..read]);
            },
        };
    }
}

/// # Reads bytes from a source and converts them into a string
///
/// ## See also
///
/// [`::read()`](fn.read.html)
pub fn read_to_string(src: &mut Read, limit: Option<usize>) -> io::Result<String> {
    String::from_utf8(read(src, limit)?).map_err(|e| Error::new(ErrorKind::InvalidInput, e))
}

/// # Reads a file
///
/// ## See also
///
/// [`::read()`](fn.read.html)
pub fn read_file<P>(file: P, limit: Option<usize>) -> io::Result<Vec<u8>> where P: AsRef<Path> {
    read(&mut BufReader::new(File::open(file)?), limit)
}

/// # Reads a file and converts its content into a string
///
/// ## See also
///
/// [`::read()`](fn.read.html), [`::read_to_string()`](fn.read_to_string.html)
pub fn read_file_to_string<P>(file: P, limit: Option<usize>) -> io::Result<String> where P: AsRef<Path> {
    read_to_string(&mut BufReader::new(File::open(file)?), limit)
}
