import { ComponentTypes, MessageFlags, Shard } from "oceanic.js";
import { client } from ".";
import { Constants } from "./Constants";
import { db } from "./database";
import {
	ActionRow,
	Button,
	ComponentMessage,
	Container,
	Divider,
	Section,
	Separator,
	TextDisplay
} from "~/components";
import { selfappReq } from "./selfappReq";
import { User } from "./components/User";

export async function setupJoinRequestHandler(shard: Shard) {
	shard.ws?.on("message", async (d) => {
		const data = JSON.parse(d.toString("utf8"));
		if (!data.t) return;
		if (data.t.startsWith("GUILD_JOIN_REQUEST")) {
			const applicationData = data.d;
			switch (data.t) {
				case "GUILD_JOIN_REQUEST_UPDATE": {
					switch (applicationData.status) {
						case "SUBMITTED": {
							const pendingMsg =
								await client.rest.channels.createMessage(
									Constants.PENDING_CHANNEL_ID,
									<ComponentMessage>
										<TextDisplay>Placeholder</TextDisplay>
									</ComponentMessage>
								);
							await db.run(
								"INSERT INTO applications (id, user_id, status, message_id, channel_id) VALUES (?, ?, 0, ?, ?)",
								applicationData.request.id,
								applicationData.request.user_id,
								pendingMsg.id,
								pendingMsg.channelID
							);

							break;
						}
					}
					break;
				}
				case "GUILD_JOIN_REQUEST_DELETE": {
					const application = await db.get(
						"SELECT * FROM applications WHERE id=?",
						applicationData.id
					);
					if (application) {
						await db.run(
							"DELETE FROM applications WHERE id=?",
							applicationData.id
						);
						await client.rest.channels.deleteMessage(
							application.channel_id,
							application.message_id
						);
					}
					await client.rest.channels.createMessage(
						Constants.REJECTION_CHANNEL_ID,
						<ComponentMessage>
							<Container accentColor={0xffaaaa}>
								<TextDisplay>
									## Join request withdrawn
								</TextDisplay>
								<Divider />
								<User id={applicationData.user_id} />
								<Divider />
								<TextDisplay>### Application</TextDisplay>
								{application ? (
									<TextDisplay>User has applied</TextDisplay>
								) : (
									<TextDisplay>
										User hasn't applied
									</TextDisplay>
								)}
							</Container>
						</ComponentMessage>
					);
					break;
				}
			}
		}
	});
}
