##########################################################################
#
# Package.py: store the Package object information.
#
#  Python-CDD is a library to make easier to build applications to
#  Custom Debian Distributions.
#  See http://projetos.ossystems.com.br/python-cdd for more information.
#
# ====================================================================
# Copyright (c) 2002-2005 O.S. Systems.	 All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
#########################################################################
# Authors: Otavio Salvador <otavio@ossystems.com.br>
#		   Nat Budin <natb@brandeis.edu>
#		   Free Ekanayaka <free@agnula.org>
"""
Classes to represent source and binary packages
"""

import apt_pkg
import logging
log = logging.getLogger("cdd.FileSystem")


class Package:
	"""
	This class encapsulates a binary debian package as represented in an apt
	Packages file.
	"""
	def __init__(self, section):
		self._fields = {}
		self._fields.update(section)

		# Handle dependencie fields
		for field in ('Suggests', 'Recommends',
					  'Depends', 'Pre-Depends', 'Conflicts'):
			if self._fields.has_key(field):
				self._replaceField(field, apt_pkg.parse_depends(self._fields[field]))

		if self._fields.has_key('Provides'):
			self._replaceField('Provides', self._fields['Provides'].split(', '))

		# Point to the functions
		self.has_key = self._fields.has_key
		self.keys = self._fields.keys
		self.__getitem__ = self._fields.get

	def _replaceField(self, field, value):
		self._fields[field + "-orig"] = self._fields[field]
		self._fields[field] = value

	def dump(self):
		"""
		Return a string containing the package stanza
		"""
		keys = self.keys()
		keys = self.keys()
		stanzaParts = []

		for field in ('Package', 'Essential', 'Priority', 'Section', 'Installed-Size',
					  'Maintainer', 'Architecture', 'Version', 'Replaces',
					  'Provides-orig', 'Depends-orig', 'Pre-Depends-orig',
					  'Suggests-orig', 'Recommends-orig',
					  'Conflicts-orig', 'Filename', 'Size',
					  'MD5sum', 'SHA1', 'SHA256',
					  'Description', 'Tag', 'Build-Essential',
					  'Kernel-Version', 'Installer-Menu-Item',
					  'Enhances', 'Homepage', 'Package-Type'):
			if self._fields.has_key(field):
				keyName = field
				if field.endswith('-orig'):
					keyName = field[:-5]
				stanzaParts.append("%s: %s" % (keyName,  self._fields[field]))
				keys.remove(field)

		stanzaParts.append("")
		stanzaParts.append("")
		return "\n".join(stanzaParts)

	def __repr__(self):
		return "Package: %s" % self["Package"]


class SourcePackage(Package):
	"""
	This class encapsulates a debian source package as represented in an apt
	Sources file.

	The class transforms the `Files` field provided by the Sources file into a
	list of dictionaries with three fields: `name`, `md5sum` and `size`.
	"""
	def __init__(self, section):
		# First, we load the default information
		Package.__init__(self, section)

		# Handle Build-Depends field
		for field in ('Build-Depends', 'Build-Depends-Indep',
					  'Build-Conflicts', 'Build-Conflicts-Indep'):
			if self._fields.has_key(field):
				self._fields[field + "-orig"] = self._fields[field]
				self._fields[field] = apt_pkg.parse_src_depends(self._fields[field])

		for field in ('Binary', 'Uploaders'):
			if self._fields.has_key(field):
				self._fields[field + "-orig"] = self._fields[field]
				self._fields[field] = self._fields[field].split(', ')

		# Now, let's do the trick ;-)
		self._fields['Files-orig'] = "\n " + self._fields['Files']
		files = self._fields['Files'].split(' ')
		self._fields['Files'] = []
		for i in range(0, len(files), 3):
			tmpdict = {}
			tmpdict['md5sum'] = files[i]
			tmpdict['size'] = files[i+1]
			if files[i+2][len(files[i+2])-1:len(files[i+2])] == "\n":
				tmpdict['name'] = files[i+2][:-1]
			else:
				tmpdict['name'] = files[i+2]
			self._fields['Files'].append(tmpdict)

	def dump(self):
		"""
		Return a string containing the package stanza
		"""
		keys = self.keys()
		stanza = ""
		for field in ['Package', 'Binary-orig', 'Version',
					  'Priority', 'Section', 'Maintainer',
					  'Build-Depends-orig', 'Build-Depends-Indep-orig',
					  'Build-Conflicts-orig', 'Build-Conflicts-Indep-orig',
					  'Architecture', 'Standards-Version', 'Format',
					  'Directory', 'Files-orig', 'Uploaders-orig']:
			if self._fields.has_key(field):
				if field.endswith('-orig') and field != 'Files-orig':
					stanza += field[:-5] + ": " + self._fields[field] + "\n"
				elif field == 'Files-orig':
					stanza += field[:-5] + ":" + self._fields[field] + "\n"
				else:
					stanza += field + ": " + self._fields[field] + "\n"
				keys.remove(field)

		return stanza + "\n"

