#!/usr/bin/env python3

import json as _json
import datetime as _datetime


def sql_format(
	value
):
	if (value is None):
		return "NULL"
	else:
		if (type(value) == bool):
			return ('TRUE' if value else 'FALSE')
		elif (type(value) == int):
			return ("%u" % value)
		elif (type(value) == str):
			return ("'%s'" % value)
		else:
			raise ValueError("unhandled type: " + str(type(value)))
			

def string_coin(
	template,
	arguments
):
	result = template
	for (key, value, ) in arguments.items():
		result = result.replace("{{%s}}" % key, value)
	return result


def file_read(
	path
):
	handle = open(path, "r")
	content = handle.read()
	handle.close()
	return content
	

def datetime_convert(
	datetime
):
	return (
		None
		if
		(datetime is None)
		else
		string_coin(
			"{{timezone_shift}}|{{year}}-{{month}}-{{day}}{{macro_time}}",
			{
				"timezone_shift": ("%02u" % datetime["timezone_shift"]),
				"year": ("%04u" % datetime["date"]["year"]),
				"month": ("%02u" % datetime["date"]["month"]),
				"day": ("%02u" % datetime["date"]["day"]),
				"macro_time": (
					""
					if
					(datetime["time"] is None)
					else
					string_coin(
						"T{{hour}}:{{minute}}:{{second}}",
						{
							"hour": ("%02u" % datetime["time"]["hour"]),
							"minute": ("%02u" % datetime["time"]["minute"]),
							"second": ("%02u" % datetime["time"]["second"]),
						}
					)
				)
			}
		)
	)
	

def main(
):
	data = _json.loads(file_read("data/example.kal.json"))
	for user in data["users"]:
		print(
			string_coin(
				"INSERT INTO users(id,name) VALUES ({{id}},{{name}});\n",
				{
					"id": sql_format(user["id"]),
					"name": sql_format(user["object"]["name"]),
				}
			)
		)
	ids = {
		"calendars": 0,
		"local_resource": 0,
		"caldav_resource": 0,
	}
	for calendar in data["calendars"]:
		ids["calendars"] += 1
		if (calendar["object"]["kind"] == "concrete"):
			ids["local_resource"] += 1
			print(
				string_coin(
					"INSERT INTO local_resources(id) VALUES ({{id}});\n",
					{
						"id": sql_format(ids["local_resource"])
					}
				)
			)
			for event in calendar["object"]["data"]["events"]:
				print(
					string_coin(
						"INSERT INTO local_resource_events(local_resource_id,name,begin,end,location,description) VALUES ({{local_resource_id}},{{name}},{{begin}},{{end}},{{location}},{{description}});\n",
						{
							"local_resource_id": sql_format(ids["local_resource"]),
							"name": sql_format(event["name"]),
							"begin": sql_format(datetime_convert(event["begin"])),
							"end": sql_format(datetime_convert(event["end"])),
							"location": sql_format(event["location"]),
							"description": sql_format(event["description"]),
						}
					)
				)
			print(
				string_coin(
					"INSERT INTO resources(kind,sub_id) VALUES ({{kind}},{{sub_id}});\n",
					{
						"kind": sql_format("local"),
						"sub_id": sql_format(ids["local_resource"])
					}
				)
			)
		elif (calendar["object"]["kind"] == "caldav"):
			ids["caldav_resource"] += 1
			print(
				string_coin(
					"INSERT INTO caldav_resources(id,url,read_only) VALUES ({{id}},{{url}},{{read_only}});\n",
					{
						"id": sql_format(ids["caldav_resource"]),
						"url": sql_format(calendar["object"]["data"]["url"]),
						"read_only": sql_format(calendar["object"]["data"]["read_only"]),
					}
				)
			)
			print(
				string_coin(
					"INSERT INTO resources(kind,sub_id) VALUES ({{kind}},{{sub_id}});\n",
					{
						"kind": sql_format("caldav"),
						"sub_id": sql_format(ids["caldav_resource"])
					}
				)
			)
		else:
			raise ValueError("invalid")
		print(
			string_coin(
				"INSERT INTO calendars(id,name,public,resource_id) VALUES ({{id}},{{name}},{{public}},LAST_INSERT_ROWID());\n",
				{
					"id": sql_format(ids["calendars"]),
					"name": sql_format(calendar["object"]["data"]["name"]),
					"public": sql_format(not calendar["object"]["data"]["private"]),
				}
			)
		)
		for member in calendar["object"]["data"].get("users", []):
			print(
				string_coin(
					"INSERT INTO calendar_members(calendar_id,user_id,role) VALUES ({{calendar_id}},{{user_id}},{{role}});\n",
					{
						"calendar_id": sql_format(ids["calendars"]),
						"user_id": sql_format(member["id"]),
						"role": sql_format(member["role"]),
					}
				)
			)
	

main()
