const fs = require('fs');
const merge = require('lodash/merge')

const wordpressPassword = process.env.WORDPRESS_PASSWORD;
const auth = Buffer.from(`lewis:${wordpressPassword}`).toString('base64');

class PostCache {
	constructor() {
		this.readCache();
	}

	readCache() {
		if (!fs.existsSync(".cache")) {
			fs.mkdirSync(".cache");
		}
		
		if (!fs.existsSync(".cache/wordpress_post_fetch.json")) {
			this.last_read_date = null;
			this.posts = {};
		} else {
			const data = JSON.parse(fs.readFileSync(".cache/wordpress_post_fetch.json"));
			this.last_read_date = new Date(data.last_read_date);
			this.posts = data.posts;
		}
	}

	writeCache() {
		fs.writeFileSync(".cache/wordpress_post_fetch.json", JSON.stringify(this, null, 2));
	}

	async fetchCommentsByType(type = "comment") {
		const params = new URLSearchParams();
		params.set("per_page", 100);
		params.set("type", type);

		if (this.last_read_date) {
			params.set("modified_after", this.last_read_date.toISOString());
		}

		const response = await fetch(`https://cms.lewisdale.dev/wp-json/wp/v2/comments?${params.toString()}`, {
			headers: {
				"Authorization": `Basic ${auth}`
			}
		});
		return await response.json()
	}

	async fetchComments() {
		const likes = await this.fetchCommentsByType("like");
		const mentions = await this.fetchCommentsByType();
		const reposts = await this.fetchCommentsByType("repost");
		
		const comments = [...likes, ...mentions, ...reposts];

		comments.forEach(comment => {
			if (this.posts[comment.post]) {
				this.posts[comment.post].comments[comment.id] = comment;
			}
		});
	}

	async fetchPosts() {
		const params = new URLSearchParams();
		params.set("per_page", 100);

		if (this.last_read_date) {
			params.set("modified_after", this.last_read_date.toISOString());
		}

		const response = await fetch(`https://cms.lewisdale.dev/wp-json/wp/v2/posts?${params.toString()}`, {
			headers: {
				"Authorization": `Basic ${auth}`
			}
		});
		const posts = await response.json();

		posts.forEach(post => {
			this.posts[post.id] = merge({ comments: {} }, this.posts[post.id], post);
		});
	}

	async fetchLatest() {
		await this.fetchPosts();
		await this.fetchComments();
		await this.fetchTags();

		this.last_read_date = new Date();
		this.writeCache();
	}

	async fetchTags() {
		const params = new URLSearchParams();
		params.set("per_page", 100);

		const response = await fetch(`https://cms.lewisdale.dev/wp-json/wp/v2/tags?${params.toString()}`, {
			headers: {
				"Authorization": `Basic ${auth}`
			}
		});
		const tags = await response.json();
		this.tags = tags.reduce((tagMap, tag) => ({...tagMap, [tag.id]: tag }), {});
	}
}

const cache = new PostCache();

// module.exports = async function() {
//     await cache.fetchLatest();
//     return cache;
// }