import requests

from lib.forge_base import ForgeBase
import os

class GitlabForge(ForgeBase):
	def __init__(self):
		self.token = None
	
	def from_env(self):
		self.token = os.environ.get("GITLAB_TOKEN")
		self.domain = os.environ.get("GITLAB_DOMAIN")
		self.project_id = os.environ.get("GITLAB_PROJECT_ID")
	
	def does_pr_already_exist(self, from_branch):
		url = "https://{}/api/v4/projects/{}/merge_requests?state=opened&source_branch={}&target_branch={}".format(self.domain, self.project_id, from_branch, "main")
		req = requests.get(url)
		req.raise_for_status()

		if len(req.json()) == 0:
			return False
		else:
			return req.json()[0]["web_url"]
	
	def make_pr_between_branches(self, from_branch, to_branch, title, body):
		url = "https://{}/api/v4/projects/{}/merge_requests".format(self.domain, self.project_id)
		req = requests.post(url, params={
			"source_branch": from_branch,
			"target_branch": to_branch,
			"title": title,
			"description": body
		}, headers = {
			"PRIVATE-TOKEN": self.token
		})
		req.raise_for_status()
		return req.json()["web_url"]