#!/usr/bin/env python

import sys
import os
import urllib2

from common.buildtrigger import trigger_info, trigger_next, get_pending_builds_with_parameter, cancel_pending_build_with_id, get_running_builds_with_parameter, cancel_running_build_with_id
from common.gbsutils import gbs_update_dashboard
from datetime import datetime

def menu_options(menu):
    return ["", "Deps/Full Build", "Remove Packages", "New project gbs fullbuild", "Link Project Upgrade"].index(menu)

def _is_candidate_actions(actions, tag):
    for action in actions:
        if not 'parameters' in action:
            continue
        for param in action.get('parameters'):
            name = param.get('name')
            value = param.get('value')
            if name == 'TRIGGER_INFO' and value:
                pending_info = trigger_info(value, show=False)
                if pending_info.get('tag') == tag or pending_info.get('gbsbuild_tag') == tag \
                    or ('gbsbuild_dic' in pending_info and pending_info['gbsbuild_dic'].get('gbsbuild_tag') == tag):
                    return True
    return False

def abort_pending_builds(tag):

    pending_build_queue = get_pending_builds_with_parameter()
    if not pending_build_queue:
        return False
    for _queue in pending_build_queue:
        if 'task' not in _queue or 'name' not in _queue.get('task') \
            or _queue.get('task').get('name') not in os.getenv('ABORTING_JOBS').split(','):
            continue
        job = _queue.get('task').get('name')
        queue_id = _queue.get('id')
        if _is_candidate_actions(_queue.get('actions'), tag):
            print 'Aborting [%s] pending build [%s]' % (job, queue_id)
            cancel_pending_build_with_id(queue_id)

def abort_running_builds(tag):

    for job in os.getenv('ABORTING_JOBS').split(','):
        ret_dict = get_running_builds_with_parameter(job)
        for build in ret_dict["builds"]:
            build_id = build.get('number')
            building = build.get('building')
            if not building:
                continue
            if _is_candidate_actions(build.get('actions'), tag):
                print 'Aborting [%s] running build [%s]' % (job, build_id)
                cancel_running_build_with_id(job, build_id)

def abort_build(contents):
    print 'ABORT %s' % contents.get("tag")
    aborting_job_list = os.getenv('ABORTING_JOBS').split(',')
    print aborting_job_list

    tag = contents.get("tag")
    abort_pending_builds(tag)
    abort_running_builds(tag)

    bypass_data = {
        "mode"           : "aborted",
        "tag"            : contents.get("tag"),
        "submitter"      : contents.get("user_email"),
        "reason"         : {"by": contents.get("user_email"), "comment": contents.get("comment")}
        }
    print bypass_data
    gbs_update_dashboard(bypass_data, via='direct_call')

def release_snapshot(contents):
    print 'Release Snapshot %s' % contents.get("tag")
    #TODO: Do your job
    bypass_data = {
        "mode"           : "release_snapshot",
        "tag"            : contents.get("tag"),
        "release_type"   : contents.get("release_type"),
        "submitter"      : contents.get("user_email"),
        "version"        : contents.get("version"),
        "url"            : "https://download.tizen.org/.gbsdbbuild/release/%s/%s/%s" % (contents.get("release_type"), contents.get("version"), contents.get("tag")),
        "comment"        : contents.get("comment")
        }
    print bypass_data
    gbs_update_dashboard(bypass_data, via='direct_call')

def get_snapshot_id(obs_prj):
    curr_date = os.getenv('SPECIFIC_DATE_BUILD')
    if not curr_date:
        curr_date=datetime.today().strftime("%Y%m%d")
    basic_url= os.getenv('URL_PUBLIC_REPO_BASE') + '/snapshots/tizen/'
    profile = obs_prj.replace("Tizen:","").replace(":","-").lower()
    profile_url = basic_url+profile+'/'
    snapshot_id_prefix = "tizen-"+profile

    profile_url_content=urllib2.urlopen(profile_url).read()

    if profile_url_content.find(curr_date) == -1:
        return (None,None)

    if os.getenv("USE_WHICH_SNAPSHOT") == "first":
        snapshot_num_used = curr_date+'.1'
    else:
        last_snapshot_num='1'
        for line in profile_url_content.split('\n'):
            if line.find(curr_date) != -1:
                snapshot_num=line.split('<a href="'+snapshot_id_prefix+'_')[1].split('/"')[0].split('.')[1]
                if int(snapshot_num) > int(last_snapshot_num):
                    last_snapshot_num = snapshot_num
        snapshot_num_used = curr_date+"."+last_snapshot_num

    curr_time = datetime.now().strftime('%Y%m%d.%H%M%S')
    snapshot_id=snapshot_id_prefix+"_"+snapshot_num_used
    tag_name="RELEASE/"+snapshot_id_prefix.upper()+"/"+snapshot_num_used+'/'+curr_time

    return (snapshot_id,tag_name)

def release_build():
    print "Start release build (periodic build)"

    for obs_prj in os.getenv("DAILY_BUILD_OBS_PROJECTS").split(' '):
        (snapshot,tag) = get_snapshot_id(obs_prj)
        print "snapshot:%s tag:%s" %(snapshot,tag)
        if not snapshot:
            print "Skip release build for %s because there is no snapshot created today" %obs_prj
            continue

        bypass_data = {
            "gbs_type"       : "Release Build",
            "tag"            : tag,
            "source_snapshot": snapshot,
            "main_project"   : obs_prj,
            "mode"           : "queued",
            }
        gbs_update_dashboard(bypass_data, via='direct_call')
        trigger_next("gbs-dashboard-build_%s" % tag.replace('/', '_'), bypass_data)

def ref_fullbuild(contents):
    print "Start reference snapshot fullbuild"

    build_profile_snapshot_id = contents.get("build_profile_snapshot_id")
    snapshot = build_profile_snapshot_id['snapshot_id']
    obs_prj = build_profile_snapshot_id['obs_prj']
    snapshot_num = snapshot.split('_')[-1]
    curr_time = datetime.now().strftime('%Y%m%d.%H%M%S')
    tag = 'REF/'+obs_prj.replace(':','-').upper()+'/'+snapshot_num+'/'+curr_time
    print "snapshot:%s tag:%s" %(snapshot,tag)

    bypass_data = {
        "gbs_type"       : "Release Build",
        "tag"            : tag,
        "source_snapshot": snapshot,
        "main_project"   : obs_prj,
        "mode"           : "queued",
        "git_ref_mapping_info": contents['git_ref_mapping_info'],
            }
#    submitter='sk7.park@samsung.com'
#    transform_packages=[{'platform/core/dotnet/build-tools': {'commit': '5bc00509597ae289c30bf4498bbb96e51dfe13b5', 'image': 'include', 'build': 'include'}}]
#    bypass_data = {
#        "gbs_type"       : "Dependency Build",
#        "tag"            : tag,
#        "source_snapshot": snapshot,
#        "main_project"   : obs_prj,
#        "mode"           : "queued",
#        "submitter"      : contents.get("user_email"),
#        "packages"       : transform_packages
#        }

    gbs_update_dashboard(bypass_data, via='direct_call')
    trigger_next("gbs-dashboard-build_%s" % tag.replace('/', '_'), bypass_data)


def main():
    """The main body"""

    # If it is not triggered by trigger_next, consider this build as release buil
    if os.getenv("TRIGGER_INFO") == None:
        release_build()
        return

    contents = trigger_info(os.getenv("TRIGGER_INFO"))

    if contents.get("menu", None) == "Abort":
        abort_build(contents)
        return

    if contents.get("menu", None) == "Release Snapshot":
        release_snapshot(contents)
        return

    if contents.get("menu", None) == "Ref Fullbuild":
        ref_fullbuild(contents)
        return

    transform_packages = []
    for x in contents.get("repo_commit"):
        transform_packages.append(
            {x["git_path"]: {
                "commit": x["commit_id"],
                "build": "include" if x["include_build"] == 1 else "exclude",
                "image": "include" if x["include_image"] == 1 else "exclude"}
            })

    bypass_data = {
        "gbs_type"       : contents.get("menu"),
        "tag"            : contents.get("tag"), 
        "source_snapshot": contents.get("snapshot"), 
        "main_project"   : contents.get("project"), 
        "mode"           : "queued", 
        "submitter"      : contents.get("user_email"),
        "packages"       : transform_packages
        }

    gbs_update_dashboard(bypass_data, via='direct_call')
    trigger_next("gbs-dashboard-build_%s" % contents.get("tag").replace('/', '_'), bypass_data)


if __name__ == '__main__':
    sys.exit(main())

