#!/usr/bin/env python3
import urllib3
import sys
import os
import json
import re
from datetime import datetime
import urllib.parse
import requests
import time

urllib3.disable_warnings()
projects_url = 'https://bitbucket.test.com/rest/api/1.0/projects'
project_key = 'AMA'
batch_size = 100
workspace = os.getenv('WORKSPACE', os.getcwd())
bitbucket_jenkins_token = os.getenv('BITBUCKET_JENKINS_TOKEN', None)


def json_serial(obj):
    if isinstance(obj, datetime):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")


def json_print(json_obj):
    return json.dumps(json_obj, indent=4, sort_keys=True, default=json_serial)


def request_get(url):
    authorization = "Bearer " + bitbucket_jenkins_token
    headers = {'Content-type': 'application/json', "Authorization": authorization}
    r = requests.get(url, headers=headers, verify=False, timeout=60)
    return r


def info(msg):
    print('\033[34m[Info]\033[0m {}'.format(msg))
    return


def warn(msg):
    print('\033[33m[Warn]\033[0m {}'.format(msg))
    return


def error(msg):
    print('\033[31m[Error]\033[0m {}'.format(msg))
    sys.exit(1)


def get_repo_id(url):
    response = request_get(url)
    jdata = json.loads(response.text)
    return jdata['id']


def main():
    start_time = time.time()
    info('Start comparing Android mobile app dev and master branch')
    app_change_size = 0
    app_project = '{}/{}/repos/android-patient-app'.format(projects_url, project_key)
    app_repo_id = get_repo_id(app_project)
    if app_repo_id is None:
        error('Check log for error message')
    app_from = urllib.parse.quote_plus('refs/heads/dev')
    app_to = urllib.parse.quote_plus('refs/heads/master')
    app_compare_branch = 'compare/commits?from={}&to={}&fromRepo={}&limit=1'.format(app_from, app_to, app_repo_id)
    app_url = '{}/{}'.format(app_project, app_compare_branch)
    response = request_get(app_url)
    if int(response.status_code) == 200:
        # info('Headers: {}'.format(dict(response.headers)))
        # info('Encoding: {}'.format(response.encoding))
        # info(str(response.text))
        # info('Text: {}'.format(response.json()))
        app_change_size = response.json()['size']
        if app_change_size == 0:
            info('APA App: No change between branches refs/heads/dev and refs/heads/master')
        else:
            info('APA App: There are changes between branches refs/heads/dev and refs/heads/master')
    else:
        error('HTTP error {}'.format(response.status_code))
        return 1
    if app_change_size == 0:
        info('APA: Remove build.properties')
        if os.path.exists(workspace + '/build.properties'):
            os.remove(workspace + '/build.properties')
    else:
        info('APA: Triggering dev2master and run INT promotion')
    info('Finished - execution time %.2f seconds' % (time.time() - start_time))
    return


if __name__ == "__main__":
    main()
