#
#  $Id: Address.py,v 1.2 1999/12/11 12:35:11 rob Exp $
#
#  Copyright 1998-1999 Rob Tillotson <robt@debian.org>
#  All Rights Reserved
#
#  Permission to use, copy, modify, and distribute this software and
#  its documentation for any purpose and without fee or royalty is
#  hereby granted, provided that the above copyright notice appear in
#  all copies and that both the copyright notice and this permission
#  notice appear in supporting documentation or portions thereof,
#  including modifications, that you you make.
#
#  THE AUTHOR ROB TILLOTSON DISCLAIMS ALL WARRANTIES WITH REGARD TO
#  THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
#  AND FITNESS.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
#  SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
#  RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
#  CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
#  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE!
#
"""Address Book.

  This module handles databases in the format used by the built-in
  address book application.

  Format of an Address record:
    - a longword, split into nybbles:
        0, 0
	phone # entry to show in list
	phone #4 type
	phone #3 type
	phone #2 type
	phone #1 type
	phone #0 type
    - a longword field mask
    - a pad byte of 0x00
    - fields: only the fields actually used appear in the data; each is
        null terminated.  If a field is used, its corresponding bit
	(last name = bit 0, first name = bit 1, etc.) is set in the
	field mask.  (Notice that the format is easily extensible to
	32 fields from the current 19, at no cost to existing records...
	although observe some strange things in the AppInfo regarding
	field names.)
"""

__version__ = '$Id: Address.py,v 1.2 1999/12/11 12:35:11 rob Exp $'

__copyright__ = 'Copyright 1998-1999 Rob Tillotson <robt@debian.org>'

import Pyrite
import Pyrite.Connector
from Pyrite import FLD_STRING, FLD_INT, FLD_UNKNOWN, FLD_LIST, _
from Pyrite import Blocks

import struct, re, quopri, operator, string

class Connector(Pyrite.Connector.Connector):
    name = 'Address'
    version = Pyrite.version
    author = Pyrite.author
    url = ''
    description = _("The built in address book.")

    def __init__(self, *a, **kw):
	apply(Pyrite.Connector.Connector.__init__, (self,)+a, kw)
	self.default_name = 'AddressDB'
	self.default_class = Database
	self.default_creator = 'addr'
	self.default_type = 'DATA'
    
    def classify(self, info={}):
	if info.get('type') == 'DATA' and info.get('creator') == 'addr':
	    return Database
	

# Note: the field names here are in the order of appearance in the data!
_field_names = ['lastname', 'firstname', 'company', 'phone1', 'phone2', 'phone3',
		'phone4', 'phone5', 'address', 'city', 'state', 'zip', 'country',
		'title', 'custom1', 'custom2', 'custom3', 'custom4', 'note']
_fields = {}
map(lambda k,d=_fields: operator.setitem(d,k, (FLD_STRING, '')), _field_names)
_fields['showPhone'] = (FLD_INT, 0, 0, 5)
_fields['phoneLabels'] = (FLD_LIST, [0,0,0,0,0], 5, 5)

class Record(Blocks.Record):
    def __init__(self, *a, **kw):
	self.fields = _fields
	apply(Blocks.Record.__init__, (self,)+a, kw)
	
    def unpack(self, raw):
	self.raw = raw
	b0, b1, b2 = struct.unpack('>xBBB', raw[:4])
	self.data['showPhone'] = (int(b0) >> 4) & 0x0f
	self.data['phoneLabels'][4] = int(b0) & 0x0f
	self.data['phoneLabels'][3] = (int(b1) >> 4) & 0x0f
	self.data['phoneLabels'][2] = int(b1) & 0x0f
	self.data['phoneLabels'][1] = (int(b2) >> 4) & 0x0f
	self.data['phoneLabels'][0] = int(b2) & 0x0f

	c = struct.unpack('>L', raw[4:8])[0]
	raw = raw[9:] # there is apparently a pad byte?
	for i in range(0, len(_field_names)):
	    if (c & (1 << i)) and raw:
		self.data[_field_names[i]], raw = string.split(raw, '\0', 1)

    def pack(self):
	c = 0
	for x in range(0, len(_field_names)):
	    if self.data[_field_names[x]]: c = c | (1 << x)
	raw = struct.pack('>bBBBLb', 0,
			  (((self.data['showPhone'] & 0x0f) << 4) |
			   (self.data['phoneLabels'][4] & 0x0f)),
			  (((self.data['phoneLabels'][3] & 0x0f) << 4) |
			   (self.data['phoneLabels'][2] & 0x0f)),
			  (((self.data['phoneLabels'][1] & 0x0f) << 4) |
			   (self.data['phoneLabels'][0] & 0x0f)),
			  c, 0)

	for x in _field_names:
	    if self.data[x]:
		raw = raw + self.data[x] + '\0'
	
	self.raw = raw
	return self.raw

	
class AppBlock(Blocks.CategoryAppBlock):
    def __init__(self, raw=None):
	self.fields = { 'labelRenamed': (FLD_LIST, [0]*22, 22, 22),
			'labels': (FLD_LIST, ['']*22, 22, 22),
			'phoneLabels': (FLD_LIST, ['']*8, 8, 8),
			'country': (FLD_INT, 0, 0, 0),
			'sortByCompany': (FLD_INT, 0, 0, 0)
			}
	Blocks.CategoryAppBlock.__init__(self, raw)

    def unpack(self, raw):
	self.raw = raw
	raw = Blocks.CategoryAppBlock.unpack(self, raw)

	lr = struct.unpack('>L', raw[:4])[0]
	raw = raw[4:]
	for x in range(0, 22):
	    if lr & (1 << x): self.data['labelRenamed'][x]= 1
	    else: self.data['labelRenamed'][x] = 0

	    self.data['labels'][x] = Pyrite.trim_null(raw[:16])
	    raw = raw[16:]

	for x in range(3, 8):
	    self.data['phoneLabels'][x-3] = self.data['labels'][x]
	for x in range(19, 22):
	    self.data['phoneLabels'][x-19+5] = self.data['labels'][x]

	self.data['country'] = int(struct.unpack('>H', raw[:2])[0])
	self.data['sortByCompany'] = int(struct.unpack('>B', raw[2:3])[0])
	# note when packing there is a pad byte at the end
	
    def pack(self):
	raw = Blocks.CategoryAppBlock.pack(self)
	lr = 0
	for x in range(0, 22):
	    if self.data['labelRenamed'][x]: lr = lr | (1 << x)
	raw = raw + struct.pack('>L', lr)

	for x in range(0, 22):
	    raw = raw + Pyrite.pad_null(self.data['labels'][x], 16)
	    # some sort of consistency check here for PhoneLabels?

	raw = raw + struct.pack('>HBb', self.data['country'],
				self.data['sortByCompany'],
				0)
	self.raw = raw
	return self.raw
    

class Database(Pyrite.Database):
    def __init__(self, *a, **kw):
	apply(Pyrite.Database.__init__, (self,)+a, kw)
	self.record_class = Record
	self.appblock_class = AppBlock
	

