import os, subprocess
import shutil
from pathlib import Path 
from classes import *
from config import Config
from logger import logger

def create_content(filename):
    filename = Path(f"{Config.CONTENT_DIR}/{filename}.md")
    if not filename.exists():
        fh = DefaultFrontmatterHeader(filename.stem)
        logger.debug(f"Creating new content {filename}")
        with filename.open("w", encoding="utf-8") as f:
            f.writelines(['---\n', fh.title, fh.date, fh.description, fh.author, fh.omit_second_title, '---\n', '\n', '\n'])

def edit_content(filename):
    logger.debug(f"Editing content {filename}")
    editor = os.environ.get('EDITOR', 'vim')
    # Create the content file if not exists
    if not Path(f"{Config.CONTENT_DIR}/{filename}.md").exists():
        create_content(filename)
    filename = Path(f"{Config.CONTENT_DIR}/{filename}.md")
    subprocess.call([editor, filename])

def init_site_old():
    logger.debug(f"Initializing new site")

    # Recreate output directory if necessary
    output_dir = Path(Config.OUTPUT_DIR)
    if output_dir.exists():
        shutil.rmtree(output_dir)
    output_dir.mkdir()

    # Create output directory subtree
    for dir in [ Path(Config.CONTENT_DIR), Path(Config.STATIC_DIR), Path(Config.TEMPLATE_DIR),
            Path(Config.OUTPUT_IMG_DIR), Path(Config.OUTPUT_CSS_DIR), Path(Config.OUTPUT_JS_DIR)]:
        dir.mkdir(exist_ok=True)    
    
    # Create "About.md" content item
    create_content("about")

def init_site():
    logger.debug(f"Initializing new site")
    site = SitePrototype
    site.init_site()

def build_site():
    logger.debug("Building site")