import requests
from requests.auth import HTTPBasicAuth

import jenkins
import json
from PyInquirer import style_from_dict, Token, prompt
import re

style = style_from_dict({
    Token.QuestionMark: '#E91E63 bold',
    Token.Selected: '#673AB7 bold',
    Token.Instruction: '',  # default
    Token.Answer: '#2196f3 bold',
    Token.Question: '',
})


def get_jobs(jenkins_answers):
    jenkins_url = jenkins_answers.get("jenkins_url")
    username = jenkins_answers.get("jenkins_username")
    token = jenkins_answers.get("jenkins_token")
    server = jenkins.Jenkins(jenkins_url, username=username, password=token)

    if "jenkins_url" in jenkins_answers and not jenkins_answers.get("path_to_data"):
        jobs = server.get_jobs(folder_depth=5)
        is_prompt_user = True

        for job in jobs:
            job_name = job.get("name")
            if job.get("_class") in ("org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject",
                                     "org.jenkinsci.plugins.workflow.job.WorkflowJob"):
                config = server.get_job_config(job.get("name"))
                replace_config(job_name, config, server, jenkins_answers)

            if is_prompt_user:
                is_okay_to_proceed = [
                    {
                        'type': 'list',
                        'name': 'is_ok',
                        'message': f"Check the job {job_name} in jenkins. Is it ok to proceed?",
                        'choices': [
                            'yes',
                            'no',
                            "don't ask me again!"
                        ]
                    }
                ]
                answers = prompt(is_okay_to_proceed, style=style)
                if answers.get("is_ok") == "no":
                    break
                else:
                    if answers.get("is_ok") == "don't ask me again!":
                        is_prompt_user = False

    elif "path_to_data" in jenkins_answers and jenkins_answers.get("path_to_data"):
        is_prompt_user = True
        with open(jenkins_answers.get("path_to_data"), "r") as jenkinsFile:
            for line in jenkinsFile.readlines():
                print(f"Reconfiguring {line}")
                line = line.replace("\n","")
                if line.endswith("/"):
                    append_api = "api/json?pretty=true"
                    json_api = f"{line}{append_api}"
                else:
                    append_api = "api/json?pretty=true"
                    json_api = f"{line}/{append_api}"

                response = requests.request("GET", json_api, auth=HTTPBasicAuth(username, token))

                if response.status_code == 200:
                    job_name = json.loads(response.content.decode())["fullName"]

                    config = server.get_job_config(job_name)

                    replace_config(job_name, config, server, jenkins_answers)

                    if is_prompt_user:
                        is_okay_to_proceed = [
                            {
                                'type': 'list',
                                'name': 'is_ok',
                                'message': f"Check the job {job_name} in jenkins. Is it ok to proceed?",
                                'choices': [
                                    'yes',
                                    'no',
                                    "don't ask me again!"
                                ]
                            }
                        ]
                    answers = prompt(is_okay_to_proceed, style=style)
                    if answers.get("is_ok") == "no":
                        break
                    else:
                        if answers.get("is_ok") == "don't ask me again!":
                            is_prompt_user = False


def replace_config(job_name, config, server, jenkins_answers):
    credentials_id = jenkins_answers.get("new_credentials_id")

    team_prefix = jenkins_answers.get("team_prefix")
    old_org = jenkins_answers.get("old_org")
    new_org = jenkins_answers.get("new_org")

    api_uri = "<apiUri>https://github.nike.com/api/v3<apiUri>"
    config = config.replace(old_org + "/", f"{new_org}/{team_prefix}.").replace(api_uri,
                                                                                "<apiUri>https://api.github.com<apiUri>")
    config = config.replace("github.nike.com", "github.com")
    for org in old_org.split(","):
        config = config.replace(org, new_org)
    if credentials_id.strip() != "":
        config = re.sub("<credentialsId>.*</credentialsId>", f"<credentialsId>{credentials_id}</credentialsId>",
                        config)
    # job_name = job.get("name")

    # change_name = [
    #
    #     {
    #         'type': 'confirm',
    #         'name': 'change_name',
    #         'message': f"Change the bmx job name {job_name} to team_prefix.<oldname>?"
    #     }
    # ]
    #
    # change_name_answers = prompt(change_name, style=style)
    #
    # if change_name_answers.get("change_name"):
    #     job_match = re.findall(r'<displayName>.*</displayName>', config)
    #     if len(job_match)>0:
    #         job_name = job_match[0].replace("displayName", "").replace("<>", "").replace("</>", "")
    #
    #         new_job_name = f"{team_prefix}.{job_name}"
    #         config = re.sub("<displayName>.*</displayName>", f"<displayName>{new_job_name}</displayName>", config)
    #     else:
    #         print("unable to change name")
    server.reconfig_job(job_name, config_xml=config)
    print(f"completed configuring {job_name}")
