<?php

require_once 'mysql_adapter.php';

use Spatie\YamlFrontMatter\YamlFrontMatter;
use Laminas\Feed\Writer\Feed;

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($post_meta["title"] == "") {
			$post_meta["title"] = "root";
		}

		if(!isset($post_meta['type'])) {
			$type = null;

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

			$ext_mapping = [
				'' => 'directory',
				'md' => 'text/markdown',
				'png' => 'image',
				'jpg' => 'image',
				'jpeg' => 'image'
			];
			
			if(isset($ext_mapping[$ext])) {
				$post_meta['type'] = $ext_mapping[$ext];
			}
			else {
				$post_meta['type'] = '?';
			}
		}
		
		if(!isset($post_meta['icon'])) {
			$icon_mapping = [
				'' => 'question',
				'text/markdown' => 'markdown',
				'directory' => 'folder',
				'image' => 'image'
			];

			$post_meta['icon'] = $icon_mapping[$post_meta['type']] ?? 'question';
		}

		$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 update_or_create_post(...$args) {
		$this->_exec("TRUNCATE feed_cache");
		parent::update_or_create_post(...$args);
	}

    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['settings'])) {
				$readme_metadata['settings'] = $post_metadata['settings'];
			}
            if(isset($post_metadata['directory'])) {
                $readme_metadata = $post_metadata['directory'];
            }
			
			$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);
		}
	}

	function try_get_cached_feed($path, $export_opt) {
		$post_cache = $this->_exec("SELECT feed_content, feed_created_on
		FROM feed_cache
		WHERE search_path=? AND export_type=?", "ss", $path, $export_opt)->fetch_assoc();

		if(!isset($post_cache)) {
			return null;
		}

		return ['feed' => $post_cache['feed_content'], 'feed_ts' => $post_cache['feed_created_on']];
	}

	function construct_feed($path) {
		$path = $this->_sanitize_path($path);

		$feed = @new Feed;
		
		$feed->setTitle("DergFeed");
		$feed->setLink("https://lucidragons.de" . $path);
		$feed->setFeedLink("https://lucidragons.de/feeds/atom" . $path, "atom");

		$feed->setDateModified(time());

		$feed->setDescription("DergenFeed for all your " . $path . " needs <3");

		$feed_posts = $this->_exec("SELECT 
			post_path,
			post_create_time, post_update_time,
			post_content,
			post_metadata
		FROM posts
		WHERE (post_path = ?) OR (post_path LIKE ?)
		ORDER BY post_create_time DESC LIMIT 200",
			"ss", $path, $path . '/%');

		while($row = $feed_posts->fetch_array(MYSQLI_ASSOC)) {
			$row = $this->_normalize_post_data($row);
			$pmeta = $row['post_metadata'];
			
			if($pmeta['type'] == 'directory') {
				continue;
			}

			$entry = $feed->createEntry();

			$entry->setTitle($row['post_path'] . '> ' . $pmeta['title']);
			$entry->setLink('https://lucidragons.de' . $row['post_path']);
			$entry->setDateModified(strtotime($row['post_update_time']));
			$entry->setDateCreated(strtotime($row['post_create_time']));

			$entry->setDescription($pmeta['brief'] ?? $pmeta['title']);

			$feed->addEntry($entry);
		}

		return $feed;
	}

	function get_laminas_feed($path, $export_opt) {
		$path = $this->_sanitize_path($path);

		$feed_cache = $this->try_get_cached_feed($path, $export_opt);

		if(isset($feed_cache)) {			
			return $feed_cache;
		}

		$feed = $this->construct_feed($path);

		$this->_exec("INSERT INTO feed_cache 
			(search_path, export_type, feed_content)
		VALUES 
			(?, 'atom', ?),
			(?, 'rss', ?)",
		"ssss", $path, $feed->export('atom'),
			$path, $feed->export('rss'));

		return $this->try_get_cached_feed($path, $export_opt);
	}
}

?>