from Utility import *
import requests
from bs4 import BeautifulSoup, element
import re
import os, glob
import Utility
from jenkinsapi import jenkins

 
# def CallChangelogAPI(url):
#     payload={}
#     headers = {
#     'Authorization': 'Basic ' + JenkinsToken
#     }
#     response = requests.request("GET", url, headers=headers, data=payload)
#     return response

# def SplitFunction(text):
#     result = text.split('<footer class=', 1)[0]
#     soup = BeautifulSoup(result, "html.parser")
#     result = soup.find(attrs={'class' : 'pane'}).find_all('div')
#     result_target_word = []
#     for item in result:
#         # tagtag = item.find('a')
#         tagtag2 = item.find('pre')
#         for br in soup.find_all("br"):
#           br.replace_with("\n")

#         cut = tagtag2.text.lower().split('internal changelog:\n')
#         if len(cut) > 1:
#             r = cut[-1]

#             r2 = r.split('\n\n')[0]
#             # r2 = r2.split('\n\n\n')[0]
#             result_target_word.append(r2)
#             r3 = r2.rstrip()
          
#             print(r3)
        
#     return result_target_word

# def TriggerChangelog(text):
#   soup = BeautifulSoup(text, "html.parser")  
#   # tag = soup.body
#   for element in soup.find_all(text=re.compile("changelog")):
#       # if "Internal changelog" == True:
#       #     print("aa")
#     print(SplitFunction(APIResponse.text))

# def GenerateChangeLogUrl(Pipeline, BuildNumber):
#   link = []
#   url = JenkinsUrl + "job/" + Pipeline + "/" + BuildNumber + "/changes"  
#   link.append(url)
#   return url

# GenerateChangeLogUrl("Production-RCCP", "50")

# # jenkins_server = Jenkins(ci_jenkins_url='https://192.168.2.71:8080/jenkins/', username='deployment', password='$z-!p.LUenR?2Hgt')
# # my_job = jenkins_server.get_job('My Job Name')
# # last_build = my_job.get_last_buildnumber()


# # url = "http://192.168.2.71:8080/jenkins/job/Production-RCCP/50/changes"; 
# APIResponse = CallChangelogAPI(GenerateChangeLogUrl("Production-RCCP", "50"))
# SplitResult = SplitFunction(APIResponse.text)
# # Changelog = TriggerChangelog(APIResponse.text)

# # print(CallChangelogAPI(GenerateChangeLogUrl("Production-RCCP", "50")).get_job("jobname").get_last_buildnumber())



# def GetLastBuiildNumber(ProjectName):
#   # Logic put here
#   return LastBuildNumber

# def GenerateChangeLogUrl(ProjectName):
#   # Call GetLastBuiildNumber(ProjectName)
#   return Url

# def GetChangeLogFromJenkins(ProjectName):
#   # gCall enerateChangeLogUrl(ProjectName)
#   # CallAPI 
#   # return unbeautiful changelog by Jenkins

# def GetChangeLog(ProjectName):
#   # gCall GetChangeLogFromJenkins(ProjectName):
#   return ChangeLog

# ProjectName = ""
# GetChangeLog(ProjectName)

def GetLastBuiildNumber(ProjectName):
  j = jenkins.Jenkins(JenkinsUrl, username=JenkinsUsername, password=JenkinsPassword)
  LastBuildNumber= j.get_job(ProjectName).get_last_buildnumber()
  return LastBuildNumber

def GenerateChangeLogUrl(ProjectName):
  url = JenkinsUrl + "job/" + ProjectName + "/" + str(GetLastBuiildNumber(ProjectName)) + "/changes"
  return url

def GetChangeLogFromJenkins(ProjectName):
  url = GenerateChangeLogUrl(ProjectName)
  payload={}
  headers = {
    'Authorization': 'Basic ' + JenkinsToken
  }
  response = requests.request("GET", url, headers=headers, data=payload)
  return response.text
  
def GetChangeLog(ProjectName):
  UnBeautifyChangeLog = GetChangeLogFromJenkins(ProjectName)
  # print(UnBeautifyChangeLog)
  # soup = BeautifulSoup(ProjectName, "html.parser")  
  # # tag = soup.body
  # for element in soup.find_all(text=re.compile("changelog")):
      # if "Internal changelog" == True:
      #     print("aa")
    # print(GetChangeLog(ProjectName))
  result = UnBeautifyChangeLog.split('<footer class=', 1)[0]
  soup = BeautifulSoup(result, "html.parser")
  result = soup.find(attrs={'class' : 'pane'}).find_all('div')
  # print(result)
  ChangeLog = []
  for item in result:
        # tagtag = item.find('a')
        tagtag2 = item.find('pre')
        for br in soup.find_all("br"):
          br.replace_with("\n")

        cut = tagtag2.text.lower().split('\nChangelog:\n')
        if len(cut) > 0:
            r = cut[-1]

            r2 = r.split('\n\n')[0]
            # r2 = r2.split('\n\n\n')[0]
            ChangeLog.append(r2)
            r3 = r2.rstrip()
          
            # print(r3)
            print(''.join(r3))
            # print(''.join(map(str, r3)))
            # lst_str = str(r3)[1:-1] 
            # print(lst_str)
            # print( convert(r3))
            # room =''.join([str(elem) for elem in r3])
            # for x in r3:
            #  r3 += '' + x
            # ' '.join(str(e)for e in r3)
            # print(listToString(r3))
            # print(GetChangeLog(ProjectName))
  return r3
ProjectName = "Staging-RCM_API"
Chg = GetChangeLog(ProjectName)
print(type(Chg))
print(Chg)

