import os
import sys
import base64
import xml.etree.cElementTree as ElementTree

from common.buildservice import BuildService
from common.buildtrigger import trigger_info
from common.send_mail import prepare_mail

class LocalError(Exception):
    """Local error exception."""
    pass

def send_mail_buildstatus(info, test_status=None):
    """ send mail about buildstatus """
    EMAIL_TITLE = "SR[%s] %s %s %s"
    EMAIL_BODY = "The status of the SR has been updated.\n" \
                 "Please check the following details.\n\n" \
                 "SR tag: %s\n" \
                 "Packages : %s\n\n" \
                 "Result\n" \
                 "Build : %s\n" \
                 "Image : %s\n" \
                 "Test : %s\n\n"

    EMAIL_FOOTER = '\n\n--------------------------------------------------------\n'\
                   'Automatically generated by backend service.\n'\
                   'Please DO NOT Reply!'
    imgsuccess, imgfailed, imgstatus = 0, 0, ''
    buildsuccess, buildfailed, buildstatus = 0, 0, ''
    submitters = info.get('submitter')

    if info.get('buildstatus'):
        for status in info.get("buildstatus"):
            buildstatus += "\n %s arch: %s (%s:%s)" \
                           % (status.get('repo'),status.get('arch'), \
                              status.get('code'),status.get('count') \
                             )
            if status.get('code') != 'succeeded':
                buildfailed += 1
            else:
                buildsuccess += 1

        buildstatus += '\n'

        if buildfailed > 0:
            title_build = 'Build(Failed)'
        else:
            title_build = 'Build(Succeeded)'
    else:
        title_build=""
        buildstatus=""

    if info.get('images'):
        for image in info.get('images'):
            if image['status'] == 'success':
                imgsuccess += 1
            if image['status'] == 'failed':
                imgfailed += 1

        if imgfailed > 0:
            title_image = 'Image(Failed)'
        else:
            title_image = 'Image(Succeeded)'
        imgstatus += "\n success (%s)  failed (%s) \n" % (imgsuccess, imgfailed)
    else:
        title_image=""
        imgstatus=""

    dashboard_url = ""
    if 'basechecker' in info.get('git_tag'):
        dashboard_url = os.path.join(os.getenv('DASHBOARD_URL'), "base_verification.code?sr=" + info.get('git_tag'))
    else:
        dashboard_url = os.path.join(os.getenv('DASHBOARD_URL'), "index.code?sr=" + info.get('git_tag'))
   
    if test_status:
        if test_status == 'S':
            title_test = 'Test(Succeeded)'
            teststatus = 'success'
        else:
            title_test = 'Test(Failed)'
            teststatus = 'failed'
    else:
        title_test =""
        teststatus =""

    #make a message
    title = EMAIL_TITLE % (info.get('git_tag'), title_build, title_image, title_test)
    email_body = EMAIL_BODY % ( info.get('git_tag'), info.get('packages'), buildstatus, imgstatus, teststatus)
    msg = 'Hello \n\n' + email_body + EMAIL_FOOTER
    print submitters
    print title
    print msg
    if submitters:
        prepare_mail("%s.env" % os.getenv('BUILD_TAG'), title, msg,
                     os.getenv('NOREPLY_EMAIL_SENDER'), submitters)

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

    obs_api = os.getenv("OBS_API_URL")
    obs_user = os.getenv("OBS_API_USERNAME")
    obs_passwd = os.getenv("OBS_API_PASSWD")

    content = trigger_info(os.getenv('TRIGGER_INFO'))

    build = BuildService(obs_api, obs_user, obs_passwd)
    if content.get('project'):
        project = content.get('project')
        test_status = content.get('status')
    else:
        project = content.get('obs_url').split('project=')[-1]
        test_status = None

    if project is None:
        raise LocalError('Please check the project (%s)' \
                         % (project))

    saved_info = build.get_info(project)
    send_mail_buildstatus(saved_info, test_status)

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

