# -*- coding: utf-8 -*-
# Copyright (c) 2019, JINGROW
# For license information, please see license.txt


import json
from typing import TYPE_CHECKING

import jingrow
from jcloud.jcloud.pagetype.app.app import new_app
from jcloud.utils import get_current_team

if TYPE_CHECKING:
	from jcloud.jcloud.pagetype.app.app import App
	from jcloud.jcloud.pagetype.release_group.release_group import ReleaseGroup


@jingrow.whitelist()
def new(app):
	if isinstance(app, str):
		app = json.loads(app)

	name = app["name"]
	team = get_current_team()

	if jingrow.db.exists("App", name):
		app_pg: "App" = jingrow.get_pg("App", name)
	else:
		app_pg: "App" = new_app(name, app["title"])
	group: "ReleaseGroup" = jingrow.get_pg("Release Group", app["group"])

	source = app_pg.add_source(
		group.version,
		app["repository_url"],
		app["branch"],
		team,
		app["github_installation_id"] if "github_installation_id" in app else None,
	)

	group.update_source(source)
	return group.name
