#
#  $Id: OldDLP.py,v 1.2 1999/12/11 12:35:12 rob Exp $
#
#  Copyright 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!
#
"""Databases on an attached Palm Computing(R) platform device.
"""

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

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

import time

import Pyrite.Store
import Pyrite
from Pyrite import _pdapalm, Database, PrefBlock, _

class DLPStore(Pyrite.Store.BaseStore):
    properties = ('read','write','create','delete','list','install')
    db_properties = ('id-unique', 'id-replace', 'id-auto-assign')
    
    def __init__(self, port='/dev/pilot', cardno=0, preconnect_hook=None,
		 postconnect_hook = None):
	Pyrite.Store.BaseStore.__init__(self)

	self.port = port
	self.cardno = cardno
	self.__socket = None
	self.dlp = None
	self.preconnect_hook = preconnect_hook
	self.postconnect_hook = postconnect_hook
	self.user_info = None
	self.reset_on_close = 0
	
    def open(self, name, mode='rws', dbclass=Database, properties=(), **kw):
	if not self.test_db_properties(properties):
	    raise RuntimeError, _("cannot provide a db with properties %s") % properties
	m = 0
	if 'r' in mode: m = m | _pdapalm.OpenDBRead
	if 'w' in mode: m = m | _pdapalm.OpenDBWrite
	if 'x' in mode: m = m | _pdapalm.OpenDBExclusive
	if 's' in mode: m = m | _pdapalm.OpenDBSecret
	self.try_connect()
	i = self.dlp.findDBInfo(0, name, None, None, self.cardno)
	db = self.dlp.open(name, m, self.cardno)
	return dbclass(db, i, mode, self.db_properties)

    def create(self, name, creator, type, flags=0, version=1,
	       dbclass=Database, properties=(), **kw):
	if not self.test_db_properties(properties):
	    raise RuntimeError, _("cannot provide a db with properties %s") % properties
	self.try_connect()
	db = self.dlp.create(name, creator, type, flags, version, self.cardno)
	i = self.dlp.findDBInfo(0, name, None, None, self.cardno)
	return dbclass(db, i, 'rws', self.db_properties)

    def delete(self, name):
	self.try_connect()
	return self.dlp.delete(name, self.cardno)

    def info(self, name):
	self.try_connect()
	return self.dlp.findDBInfo(0, name, None, None, self.cardno)

    def list(self):
	return map(lambda x: x['name'], self.listinfo())
    
    def listinfo(self, name=None, creator=None, type=None):
	l = []
	i = 0
	self.try_connect()
	while 1:
	    info = self.dlp.getDBInfo(i, 1, 0, self.cardno)
	    if not info: break
	    i = info['index']+1
	    if name is not None and info['name'] != name: continue
	    if creator is not None and info['creator'] != creator: continue
	    if type is not None and info['type'] != type: continue
	    l.append(info)
	return l

    def getpref(self, creator, id, saved=1):
	self.try_connect()
	raw, creator, id, version, saved = self.dlp.getPref(creator, id, saved)
	return (raw, version)

    def setpref(self, raw, creator, id, version=0, saved=1):
	self.try_connect()
	return self.dlp.setPref(creator, id, saved, version, raw)
    
    # --------------
    # DLP API
    # --------------
    # Note: this is a bit sparse right now, the rest will be added as
    # needed.
    def remote_version(self):
	self.try_connect()
	return self.dlp.version()

    def get_time(self):
	self.try_connect()
	return self.dlp.getTime()

    def set_time(self, t):
	self.try_connect()
	return self.dlp.setTime(t)

    def card_info(self, cardno=0):
	self.try_connect()
	return self.dlp.getCardInfo(cardno)

    def system_info(self):
	self.try_connect()
	return self.dlp.getSysInfo()

    def battery_info(self):
	self.try_connect()
	return self.dlp.getBattery()

    def get_feature(self, creator, number):
	self.try_connect()
	return self.dlp.getFeature(creator, number)

    def sync_log(self, s):
	self.try_connect()
	return self.dlp.log(s)
    
    # Preferences
    def get_preference(self, creator, id, backup=1, prefclass=PrefBlock):
	self.try_connect()
	return apply(prefclass, self.dlp.getPref(creator, id, backup))

    def set_preference(self, pref):
	self.try_connect()
	return self.dlp.setPref(pref.creator, pref.id, pref.backup,
				pref.version, pref.pack())

    # magic :)  don't ask me how to use this stuff.
    #
    # call an application on the palmtop.  ret_length is the maximum length
    # of return value you want back.
    def call_application(self, creator, type, action, data, ret_length):
	self.try_connect()
	return self.dlp.callApp(creator, type, action, data, length, maxlength)

    def call_rpc(self):
	self.try_connect()
	raise RuntimeError, "unimplemented"
    
    # What don't we have yet:
    #    dlp.dirty() - convenience to reset LastSyncPC to 0
    #    dlp.abort() - abort immediately without notifying pilot
    
    # --------------
    # Connection API
    # --------------
    def try_connect(self):
	if self.__socket is None:
	    self.connect()
	    
    def connect(self):
	if callable(self.preconnect_hook): self.preconnect_hook(self)
	self.__socket = _pdapalm.openPort(self.port)
	self.dlp = _pdapalm.accept(self.__socket)
	# set the message on the display
	self.dlp.status()
	# get user info
	self.user_info = self.dlp.getUserInfo()
	if callable(self.postconnect_hook): self.postconnect_hook(self)

    def disconnect(self, successful=1, log=_("Sync completed.")):
	if self.__socket is not None:
	    if self.reset_on_close:
		self.reset_on_close = 0
		self.dlp.reset()
	    self.user_info['lastSyncPC'] = 0x00010000
	    self.user_info['lastSyncDate'] = time.time()
	    if successful:
		self.user_info['successfulSyncDate'] = self.user_info['lastSyncDate']
	    self.dlp.setUserInfo(self.user_info)
	    self.dlp.log(log)
	    self.dlp.close()
	    self.dlp = None
	    self.__socket = None
	    self.user_info = None

    def connected(self):
	return self.__socket is not None

    def install(self, store, name):
	"""Install a database from another store to a connected handheld.

	Note that this is slightly different than the generic 'copy' method,
	because the installation process does a few extra things based on
	the contents of the database.  Theoretically you can use 'copy' to
	install databases on the handheld, but you will not get the proper
	behavior for certain databases.
	"""
	try:
	    self.delete(name)
	except:
	    pass

	idb = store.open(name, 'rs')
	
	flags = 0
	if idb.info['flagReset']: flags = flags | 0x0020
	if idb.info['flagResource']: flags = flags | 0x0001
	if idb.info['flagNewer']: flags = flags | 0x0010
	if idb.info['flagExcludeFromSync']: flags = flags | 0x0080
	if idb.info['flagAppInfoDirty']: flags = flags | 0x0004
	if idb.info['flagReadOnly']: flags = flags | 0x0002
	if idb.info['flagBackup']: flags = flags | 0x0008
	if idb.info['flagOpen']: flags = flags | 0x8000

	if name == 'Graffiti Shortcuts ':
	    flags = flags | 0x0010
	    self.reset_on_close = 1

	odb = self.create(name, idb.info['creator'], idb.info['type'],
			  flags, idb.info['version'], info=idb.info)

	try:
	    try:
		a = idb.get_appblock()
		# pad memodb appblock to fix bug here.  that belongs
		# in the appmodule, i think.
		odb.set_appblock(a)
	    except:
		pass

	    if idb.info['creator'] == 'ptch' or idb.info['flagReset']:
		self.reset_on_close = 1

	    if idb.info['flagResource']:
		for i in range(0, len(idb)):
		    r = idb[i]
		    if r.type == 'boot':
			self.reset_on_close = 1
		    l = len(r)
		    if not l:
			continue #skip empties
		    if l > 65535:
			raise RuntimeError, _("resource #%s (%s/0x%x) > 64k bytes") % (i, r.type, r.id)
		    odb.append(r)
	    else:
		for i in range(0, len(idb)):
		    r = idb[i]
		    if r.deleted or r.archived:
			continue
		    if len(r) > 65535:
			raise RuntimeError, _("record #%s (%s/0x%x) > 64k bytes") % (i, r.id)
		    odb.append(r)

	    idb.close()
	    odb.close()
	except RuntimeError, a:
	    odb.close()
	    self.delete(name)
	    raise RuntimeError, a
	except:
	    odb.close()
	    self.delete(name)
	    raise RuntimeError, _("unknown installation error")
	    
    
class Store(Pyrite.Store.Store):
    name = 'DLP'
    version = Pyrite.version
    author = Pyrite.author
    description = _("Contents of an attached device.")
    properties = ['read','write','create','delete','list','install']
    
    store_class = DLPStore
    
