#!/usr/bin/env python
# vim: ai ts=4 sts=4 et sw=4
#
# 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.


"""Get info of package or repo from manifest file
"""

import os
import gzip
import re

from common.utils import xml_to_obj

HEADER = """<?xml version="1.0" encoding="UTF-8"?>
<manifest>
  <!--<remote fetch=\"%s\" name="tizen-gerrit" review=\"%s\"/>
  <default remote="tizen-gerrit"/>-->
"""
XML_ITEM = """  <project name="%s" path="%s" revision="%s"/>\n"""
FOOTER = """</manifest>"""

def gen_repo_manifest(data, fetch_url, review_url):
    """ Generate manifest file for android repo tool
    """
    manifest_head = HEADER % (fetch_url, review_url)
    manifest_body = ""
    manifest_tail = FOOTER

    for prj_name, prj_path, revision in data:
        manifest_body += XML_ITEM % (prj_name, prj_path, revision)

    return manifest_head + manifest_body + manifest_tail

def get_package_vcs_tag(primary_md):
    """ Get package vcs tag from repo primary md
        ret_data = [(pkg_name, vcs_tag), (), ()...]
    """

    ret_data = []
    xml_file = gzip.open(primary_md)

    primary = xml_to_obj(xml_file)

    if not primary.package:
        return ret_data

    for package in primary.package:
        vcs_tag = package.version.vcs
        obs_package_name = re.search(r'(.*)-(.*)-(.*).src.rpm', package.format.sourcerpm).groups()[0]
        if vcs_tag:
            ret_data.append((obs_package_name, vcs_tag))
        else:
            ret_data.append((obs_package_name, ""))

    return ret_data

def get_repo_primary_md(path_snapshot_base, repo):
    """ Get primary md from build.xml
    """

    # return as dict in {'package_name': "VCS Tag"}
    ret_data = None

    build_info = xml_to_obj(open(os.path.join(path_snapshot_base,
                                          'build.xml')))

    for buildtarget in build_info.buildtargets.buildtarget:
        if buildtarget.name == repo:
            for repo in buildtarget.repo:
                if repo.type == 'binary' and repo.data.endswith('packages'):
                    for md_file in os.listdir(os.path.join(path_snapshot_base,
                                                           repo.data,
                                                           'repodata')):
                        if md_file.endswith('primary.xml.gz'):
                            ret_data = \
                                os.path.join(path_snapshot_base,
                                             repo.data,
                                             'repodata',
                                             md_file)
    return ret_data

def get_build_id_from_build_xml(path_snapshot_base):
    """ Get id from build.xml
    """

    build_info = xml_to_obj(open(os.path.join(path_snapshot_base,
                                          'build.xml')))

    return build_info.id

