import requests
import git
from secrets import *


def get_group_id(group):
    # Get projects inside assigned group
    # Default group for now, maybe expand more later

    get_group = requests.get("{0}/api/v3/groups?search={1}".format(gitlab_url, group),
                             headers={"PRIVATE-TOKEN": "{0}".format(private_token)})
    group_json = get_group.json()

    return group_json[0]['id']


def push_new_gitlab(group, project_dir, project):
    origin = git.Repo("{0}/{1}".format(project_dir, project))
    origin.create_remote(
        'origin', "{0}:{1}/{2}.git".format(gitlab_url, group, project))
    origin.git.add(A=True)
    origin.git.commit(m="Automated push to master")
    origin.git.push('origin', 'master')
    print("{0} pushed to gitlab".format(project))


def checkout_branch(branch_name, project_dir, project):
    g = git.cmd.Git("{0}/{1}".format(project_dir, project))
    g.checkout('HEAD', b=branch_name)


def push_existing_gitlab(branch_name, project_dir, project):
    origin = git.Repo("{0}/{1}".format(project_dir, project))
    origin.git.add(A=True)
    origin.git.commit(m="Automated push to master")
    origin.git.push('origin', branch_name)
    print("{0} pushed to gitlab on branch {1}".format(project, branch_name))


def get_project_id(group, project):
    req_id = requests.get("{0}/api/v3/projects/{1}%2F{2}".format(gitlab_url, group, project),
                          headers={"PRIVATE-TOKEN": "{0}".format(private_token)})
    req_json = req_id.json()
    project_id = req_json['id']

    return project_id


def create_pr(project_id, branch_name):
    requests.post(
        ("{0}/api/v3/projects/{1}/merge_requests?source_branch={2}&target_branch=master&title={2}").format(
            gitlab_url, project_id, branch_name), headers={"PRIVATE-TOKEN": "{0}".format(private_token)})


def get_pr_id(group, project_id):
    get_req = requests.get("{0}/api/v3/projects/{1}%2F{2}/merge_requests?state=opened".format(
        gitlab_url, group, project_id), headers={"PRIVATE-TOKEN": "{0}".format(private_token)})
    pr_id = get_req.json()
    return pr_id[0]['id']


def accept_pr(pr_id, group, project):
    requests.put(
        "{0}/api/v3/projects/{1}%2F{2}/merge_requests/{3}/merge".format(
            gitlab_url, group, project, pr_id), headers={
            "PRIVATE-TOKEN": "{0}".format(private_token)})
    print("Merge request accepted!\n")
