use serde::Serialize;
use markdown::to_html;

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


#[derive(Serialize)]
pub struct Post {
  pub title: String,
  pub date: String,
  pub url: String,
  pub description: String,
  pub tags: Vec<String>,
  pub body: String,
  pub is_year_only: bool,
}

impl Post {
  pub fn from_marky(marky: Marky) -> Post {
    Post {
      title: marky.metadata.get("title").map_or(String::from("none"), String::from),
      date: marky.metadata.get("date").map_or(String::from("none"), String::from),
      url: marky.metadata.get("url").map_or(String::from("none"), String::from),
      description: marky.metadata.get("description").map_or(String::from("none"), String::from),
      tags: tags_string_to_vec(marky.metadata.get("tags").map_or(String::from("none"), String::from)),
      is_year_only: marky.metadata.get("yearonly").map_or(false, |a| a == "true"),
      body: to_html(&marky.content),
    }
  }
}

fn tags_string_to_vec(tags: String) -> Vec<String> {
  return tags.split(",").map(String::from).collect();
}