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

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


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

impl Post {
  pub fn from_marky(marky: Marky) -> Post {
    let date = marky.metadata.get("date").map_or(String::from("none"), String::from);
    let is_year_only = marky.metadata.get("yearonly").map_or(false, |a| a == "true");

    let (year, month, day) = to_date_number(&date);
    
    let date_compare = year * 1200 + month * 100 + day;

    let mut date_printable = String::new();
    if is_year_only {
      date_printable.push_str(&year.to_string());
    } else {
      date_printable = beautify_date(day, month, year);
    }

    Post {
      title: marky.metadata.get("title").map_or(String::from("none"), String::from),
      date: date,
      date_compare: date_compare,
      date_printable: date_printable,
      url: marky.metadata.get("url").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_whitespace().map(String::from).collect();
}

// Convert yyyy-MM-dd to yyyy, MM, dd
fn to_date_number(date: &String) -> (i32, i32, i32) {
  let split: Vec<&str> = date.split("-").collect();

  if split.len() == 0 {
    return (0, 0, 0);
  }

  let year = split[0].parse::<i32>().unwrap();
  let month = split[1].parse::<i32>().unwrap();
  let day = split[2].parse::<i32>().unwrap();

  return (year, month, day);
}

fn beautify_date(day: i32, month: i32, year: i32) -> String {
  let mut date = String::new();
  if day < 10 {
    date.push_str("0");
    date.push_str(&day.to_string());
  } else {
    date.push_str(&day.to_string());
  }

  date.push_str("-");

  if month < 10 {
    date.push_str("0");
    date.push_str(&month.to_string());
  } else {
    date.push_str(&month.to_string());
  }

  date.push_str("-");

  date.push_str(&year.to_string());

  date
}