use std::fs::File;
use std::fs::DirEntry;
use std::fs::read_dir;
use std::path::Path;

use crate::markdown::marky::Marky;

use super::models::section::Section;
use super::models::post::Post;

pub fn sections() -> Vec<Section> {
  let dir = match read_dir("./raws") {
    Err(error) => panic!("Could read raws directory: {}", error),
    Ok(dir) => dir,
  };

  let mut sections: Vec<Section> = Vec::new();
  
  for entry in dir {
    let entry = match entry {
      Err(error) => panic!("Could not read file: {}", error),
      Ok(entry) => entry,
    };

    if entry.path().is_file() {
      
    } else {
      sections.push(load_section(&entry));
    }
  }  
  return sections;
}

fn load_section(dir_entry: &DirEntry) -> Section {
  let dir = match read_dir(dir_entry.path()) {
    Err(error) => panic!("Could read raws sub directory: {}", error),
    Ok(dir) => dir,
  };

  let mut section_posts: Vec<Post> = Vec::new();

  for entry in dir {
    let entry = match entry {
      Err(error) => panic!("Could not read file: {}", error),
      Ok(entry) => entry.path(),
    };

    if entry.is_file() {
      section_posts.push(load_post(&entry));
    }

  }

  let section_name = dir_entry.file_name().into_string().unwrap();
  let section_url = section_name.to_lowercase().trim().replace(" ", "_");

  println!("[LOADER] Loaded section {} with {} posts", section_name, section_posts.len());

  return Section {
    title: section_name,
    url: section_url,
    posts: section_posts,
  }
}

fn load_post(path: &Path) -> Post {
  let file = match File::open(path) {
    Err(error) => panic!("Could not read file: {}", error),
    Ok(file) => file,
  };
  let marky = Marky::from_file(&file);
  return Post::from_marky(marky);
}