<?php

require_once 'mysql_adapter.php';

use Spatie\YamlFrontMatter\YamlFrontMatter;

class PostHandler extends MySQLAdapter {
    public $data_directory;

    function __construct() {
        parent::__construct();

        $this->data_directory = 'raw';
    }

    function _normalize_post_data($post_data) {
        $post_data = parent::_normalize_post_data($post_data);

		if(!$post_data['found']) {
			return $post_data;
		}

		$post_data["post_basename"] = basename($post_data["post_path"]);

        $post_meta = $post_data['post_metadata'];

		$post_meta["title"] ??= basename($post_data["post_path"]);
		
		if(!isset($post_meta['type'])) {
			$type = null;

			$ext = pathinfo($post_data['post_basename'], PATHINFO_EXTENSION);

			$ext_mapping = [
				'' => 'directory',
				'md' => 'text/markdown',
				'png' => 'image',
			];
			
			if(isset($ext_mapping[$ext])) {
				$post_meta['type'] = $ext_mapping[$ext];
			}
		}
		
		$post_data["post_file_dir"] = '/' . $this->data_directory . $post_data["post_path"];

		$post_data['post_metadata'] = $post_meta;

    	return $post_data;
	}

    function make_post_directory($directory) {
        $data_directory = $this->data_directory . $directory;
		
		is_dir($data_directory) || mkdir($data_directory, 0777, true);

        parent::make_post_directory($directory);
    }

    function save_file($post_path, $file_path) {
		$this->bump_post($post_path);
		move_uploaded_file($file_path, $this->data_directory . $post_path);
	}

    function save_markdown_post($post_path, $post_data) {
		$frontmatter_post = YamlFrontMatter::parse($post_data);
		$post_path = $this->_sanitize_path($post_path);

		$post_content = $frontmatter_post->body();
		$post_metadata = $frontmatter_post->matter();

		if(basename($post_path) == "README.md") {
			$readme_metadata = [];
            if(isset($post_metadata['directory_data'])) {
                $readme_metadata = $post_metadata['directory_data'];
            }
			if(isset($post_metadata['settings'])) {
				$readme_metadata['settings'] = $post_metadata['settings'];
			}
			
			$this->update_or_create_post(dirname($post_path),
                $readme_metadata, $post_content);
		}

		$this->update_or_create_post($post_path, $post_metadata, $post_content);
	}

    function handle_upload($post_path, $file_path) {
		$ext = pathinfo($post_path, PATHINFO_EXTENSION);

		switch($ext) {
			case "md":
				$this->save_markdown_post($post_path, file_get_contents($file_path));

				move_uploaded_file($file_path, $this->data_directory . $post_path);
			break;
            case "mddesc":
                $this->save_markdown_post(chop($post_path, '.mddesc'), file_get_contents($file_path));
			break;
			default:
				$this->save_file($post_path, $file_path);
		}
	}
}

?>