"""this script will auto delete any sonar branch greater than 20 days """
#!/usr/bin/env python

import datetime
import argparse
from pprint import pprint
import time
import requests
from dateutil import parser as dtparser
from dateutil.tz import tzoffset

PARSER = argparse.ArgumentParser()
PARSER.add_argument('-p', '--project', type=str, default='key', action="store",
                    help="check the project name")
PARSER.add_argument('-b', '--featurebranches', type=str, default='feature', action="store",
                    help="check the feature branch name")
PARSER.add_argument('-n', '--ageofanalysis', type=int, default=20, action="store",
                    help="check the analysis date age")
PARSER.add_argument('-t', '--branchtype', type=str, default='feature', action="store",
                    help="check the branch type")
PARSER.add_argument('-a', '--autodeletebranch', type=str, default='feature', action="store",
                    help="auto delete the branches provided")
ARGS = PARSER.parse_args()

PROJECT_NAME = ARGS.project
DAYSOLD = ARGS.ageofanalysis
FEATUREBRANCH_NAME = ARGS.featurebranches
BRANCH_TYPE = ARGS.branchtype
BRANCH_NAME = ARGS.autodeletebranch


TOKEN = '7647417147bc9521e93280b23284e5580a79a229'
SONARURL = 'https://sonar-poc.devinf.allegiantair.com'
SEARCHURL = SONARURL + "/api/projects/search.json"
HEADERS = {'content-type': 'application/json'}
GITBASEURL = 'https://git.allegiantair.com:8443/rest/api/latest'
BITBUCKETHEADERS = {'Authorization': 'Bearer NTM4OTUwNDk5Njg5OjBZ3tz85yiqoTy8lnO4DLm5WfV0'}
RESP = requests.get(SEARCHURL, headers=HEADERS, auth=(TOKEN, ''))
JSONOUT = RESP.json()


FINAL_DATE_LIST = []

for field in JSONOUT['components']:
    if 'lastAnalysisDate' in field:
        FINAL_DATE_LIST.append(dtparser.parse(field['lastAnalysisDate']))

def analysisage(age):
    """return age of analysis """
    if age == DAYSOLD:
        #nowtime = datetime.datetime.now(tzoffset("None", -25200))
        #presentday_formatted = nowtime.strftime('%Y-%m-%d')
        currentday = datetime.datetime.now()
        analysisdate = currentday - datetime.timedelta(days=DAYSOLD)
        analyzedBefore = analysisdate.strftime('%Y-%m-%d')
        return analyzedBefore


analysisage(DAYSOLD)
print("Analysis Threshold Date:", analysisage(DAYSOLD))
print("No of days old:", DAYSOLD)

""" can list out the projects by date using below param
    and adding to search parameter
    like #analyzedBefore = """

ANALYSISURL = SEARCHURL + "?analyzedBefore=" + analysisage(DAYSOLD) + "&" + "q=" + BRANCH_TYPE
BRANRESP = requests.get(ANALYSISURL, headers=HEADERS, auth=(TOKEN, ''))
BRANOUT = BRANRESP.json()

PROJECTSURL = SONARURL + "/api/project_links/search"

sonarprojects = [names['key'] for names in BRANOUT['components']]
sonardict = {}



for prjs in range(len(sonarprojects)):
    sonardict[sonarprojects[prjs]] = sonarprojects[prjs].split(":")[2]

#print("sonar dict is : ", sonardict)
#print("Total Projects: ", sonardict)


bbmatch = []
def check_in_bitbucket():
    for keys, values in sonardict.items():
        PRJS = PROJECTSURL + "?projectKey=" + keys
        #print(PRJS)
        projresp = requests.get(PRJS, headers=HEADERS, auth=(TOKEN, ''))
        projout = projresp.json()
        for match in projout['links']:
            if match['name'] == 'Sources':
                if '8443' in match['url']:
                    bburl = match['url'].split("8443")[1].split('/browse')[0]
                elif '7443' in match['url']:
                    bburl = match['url'].split("7443")[1].split('/browse')[0]
                else:
                    bburl = match['url'].split(".com")[1].split('/browse')[0]
                url = GITBASEURL + bburl + '/branches'
                if not 'REPO_NAME' in url:
                    try:
                        reporeq = requests.get(GITBASEURL + bburl + "/branches", headers=BITBUCKETHEADERS)
                        while True:
                            for branch in reporeq.json()['values']:
                                try:
                                    if branch['displayId'] == values:
                                        print("this project exist in BB : ", keys)
                                        bbmatch.append(keys)
                                except (ValueError, KeyError):
                                    print("Oops")
                            if reporeq.json()['isLastPage']:
                                break
                            else:
                                reporeq = requests.get(GITBASEURL + bburl + "/branches" +
                                                       "?start=" + str(reporeq.json()['nextPageStart']), headers=BITBUCKETHEADERS)
                    except (ValueError, KeyError):
                       # print("not present:{keys}".format(keys = ""))
                        print("{keys}".format(keys = ""))
                else:
                   # print("Malformed URL in this project, branch check may b impacted", keys + ' : ' + url)
                    print("{keys}".format(keys = ""))  
check_in_bitbucket()
#print("projects existed in BB: ", bbmatch)


BAD_GIT_URL = []
BAD_PROJECTS = []

def get_bad_urls():
    for projs in sonarprojects:
        PRJS = PROJECTSURL + "?projectKey=" + projs
        #print(PRJS)
        projresp = requests.get(PRJS, headers=HEADERS, auth=(TOKEN, ''))
        projout = projresp.json()
        for match in projout['links']:
            if match['name'] == 'Sources':
                if '8443' in match['url']:
                    bburl = match['url'].split("8443")[1].split('/browse')[0]
                elif '7443' in match['url']:
                    bburl = match['url'].split("7443")[1].split('/browse')[0]
                else:
                    bburl = match['url'].split(".com")[1].split('/browse')[0]
                #print("splitted url is : ", bburl)
                try:
                    reporeq = requests.get(GITBASEURL + bburl + "/branches", headers=BITBUCKETHEADERS)
                    #print("git api url for repo access: ", GITBASEURL + bburl + "/branches")
                    urls = GITBASEURL + bburl + '/branches'
                    if 'REPO_NAME' in urls:
                        BAD_GIT_URL.append(urls)
                        BAD_PROJECTS.append(projs)
                except (ValueError, KeyError):
                    print("not present", prjs)
    return BAD_PROJECTS


#get_bad_urls()

BRANCH_KEY_LIST = []
for keys in BRANOUT['components']:
    if 'key' in keys:
        (BRANCH_KEY_LIST.append(keys['key']))

#for i in BRANCH_KEY_LIST:
#    print("project name:", i)




""" develop branch can be ignored as of now and could be used in future. """
FEATURE_BRANCH_LIST = []
DEVELOP_BRANCH_LIST = []
BUGFIX_BRANCH_LIST = []


def branch_list_type(btype):
    """This will list the branch type as per args """
    if btype == 'BRANCH_TYPE':
        for feature in BRANCH_KEY_LIST:
            if 'feature' in BRANCH_TYPE:
                FEATURE_BRANCH_LIST.append(feature)
                print("Feature Branch:", feature)
            if 'develop' in BRANCH_TYPE:
                DEVELOP_BRANCH_LIST.append(feature)
                print("Develop Branch:", feature)
            if 'bugfix' in BRANCH_TYPE:
                BUGFIX_BRANCH_LIST.append(feature)
                print("Bugfix Branch:", feature)
            if 'release' in BRANCH_TYPE:
                BUGFIX_BRANCH_LIST.append(feature)
                print("Release Branch:", feature)
            if 'hotfix' in BRANCH_TYPE:
                BUGFIX_BRANCH_LIST.append(feature)
                print("hotfix Branch:", feature)

DELETEURL = SONARURL + "/api/projects/bulk_delete"

DELETED_BRANCH_LIST = []

FINAL_DELETE_LIST = set()


TOTAL_PROJECT_LIST = set(sonardict.keys())
#print("*" * 110)
#print("TOTAL_PROJECT_LIST", TOTAL_PROJECT_LIST)
#print("*" * 110)

BBMATCH = set(bbmatch)
#print("BBMATCH", BBMATCH)
FINAL_DELETE_LIST = TOTAL_PROJECT_LIST - BBMATCH

#print("*" * 110)
#print(BRANCH_TYPE + " project existed in  BitBucket:", BBMATCH)
#print("*" * 110)

print("*" * 110)
print(BRANCH_TYPE.upper() + " Projects to be deleted:")
for f in FINAL_DELETE_LIST:
    print(f)
print("*" * 110)


def delete_release_or_hotfix():
    if len(FINAL_DELETE_LIST) > 0:
        for matches in FINAL_DELETE_LIST:
            print("response_post_body:", "requests.post" + "(" + DELETEURL
                          + "?projects=" + matches + ", " + "headers="
                          + "{'content-type': 'application/json'}"
                          + ", " + "auth=(" + TOKEN + ", " + "''" + ")")
            """requests.post(DELETEURL + "?projects="
                                  + matches, headers=HEADERS, auth=(TOKEN, ''))"""
        print(BRANCH_TYPE + " projects deleted : ", matches)
    else:
        print("Nothing to be deleted in " + BRANCH_TYPE + " projects")
def thirty_days_old_repos():
    if DAYSOLD > 30 and len(BBMATCH)> 0:
        print("30 days old project repos : ", BBMATCH)


#delete_release_or_hotfix()
#thirty_days_old_repos()
