#
# Copyright (C) 2010, 2011, 2012, 2013, 2014 Intel, Inc.
#
#    This program is free software; you can redistribute it and/or
#    modify it under the terms of the GNU General Public License
#    as published by the Free Software Foundation; version 2 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
"""Common functions used in temp packages' builds"""

import time

from common.buildservice import BuildService


class TempBuildPkgError(Exception):
    """A local Exception handler"""
    pass

class TempPackageBuild:
    """The TempPackageBuild Class"""

    def __init__(self, apiurl, apiuser, apipasswd, project, package=None):
        self._bs = BuildService(apiurl, apiuser, apipasswd)
        self.project = project
        if not package:
            pkgs = self._bs.get_package_list(self.project)
            if len(pkgs) == 1:
                self.package = pkgs[0]
        else:
            self.package = package

    def get_build_result(self):
        """ return build result of this package """
        try:
            return self._bs.get_results(self.project, self.package)
        except TempBuildPkgError, tbpe:
            print TempBuildPkgError, ":", tbpe
            return None

    def get_build_log(self, repo, arch):
        """ try to return build log, any except is assumed no build on OBS """
        try:
            # get last 200 lines if build log exceed 200 lines
            return '\n'.join(self._bs.get_build_log(self.project, "%s/%s" %
                (repo, arch), self.package).splitlines()[-200:])
        except TempBuildPkgError:
            return "No build log"

    def get_git_info(self):
        """ parse git info of this package from commit log """
        git_info = {}

        # sometimes source link does not work when repo published,
        # so retry 10 times to wait obs to fix it automatically
        retry_count = 10
        while retry_count > 0: 
            try:
                comment = self._bs.get_src_file_content(self.project,
                        self.package, 'git_info')
                break
            except TempBuildPkgError, tbpe:
                print TempBuildPkgError, ":", tbpe, 'retrying...'
                time.sleep(3)
                retry_count -= 1

        if not retry_count:
            return {}

        for line in comment.split('\n'):
            try:
                key, value = line.split(':', 1)
                git_info[key.strip()] = value.strip()
            except TempBuildPkgError:
                print '-------------------------------------'
                print 'key:value  %s' % line
        return git_info

    def del_itself(self):
        """Delete obs project though Project name"""

        self._bs.delete_project(self.project)


