#!/usr/bin/env python
# -*- coding: utf-8 -*-
# HalManager.py
#  
#  Author: Laudeci Oliveira <laudeci@gmail.com>
#          Rafael ProenÃ§a   <cypherbios@ubuntu.com>
# 
#  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; either version 2 of the
#  License, or (at your option) any later version.
# 
#  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

#python packages
import dbus

#constantes
(FSTYPE,
FSUSAGE,
CATEGORY,
PARENT,
PRODUCT,
NUM_BLOCKS,
SYSFS_PATH_DEVICE,
METHOD_NAMES,
MINOR,
IS_MOUNTED,
MODEL,
MOUNT_OPTION_UTF8,
SYSFS_PATH,
MOUNT_POINT,
HAS_DATA,
HOTPLUG_TYPE,
DESIRED_MOUNT_POINT,
SIZE,
STORAGE_DEVICE,
IGNORE,
IS_VIDEODVD,
VALID_OPTIONS,
CAPACITY,
INTERFACES,
IS_DISC,
IS_BLANK,
UNMOUNT_VALID_OPTIONS,
IS_SVCD,
DEVICE,
UDI,
IS_VOLUME,
CAPABILITIES,
IS_MOUNTED_READ_ONLY,
FSVERSION,
IS_PARTITION,
HAS_AUDIO,
IS_APPENDABLE,
METHOD_EXECPATHS,
IS_REWRITABLE,
MAJOR,
UUID,
TYPE,
METHOD_SIGNATURES,
LABEL,
BLOCK_SIZE,
IS_VCD) = range(46)

device_properties = ['volume.fstype',
'volume.fsusage',
'info.category',
'info.parent',
'info.product',
'volume.num_blocks',
'linux.sysfs_path_device',
'org.freedesktop.Hal.Device.Volume.method_names',
'block.minor',
'volume.is_mounted',
'storage.model',
'volume.policy.mount_option.utf8',
'linux.sysfs_path',
'volume.mount_point',
'volume.disc.has_data',
'linux.hotplug_type',
'volume.policy.desired_mount_point',
'volume.size',
'block.storage_device',
'volume.ignore',
'volume.disc.is_videodvd',
'volume.mount.valid_options',
'volume.disc.capacity',
'info.interfaces',
'volume.is_disc',
'volume.disc.is_blank',
'volume.unmount.valid_options',
'volume.disc.is_svcd',
'block.device',
'info.udi',
'block.is_volume',
'info.capabilities',
'volume.is_mounted_read_only',
'volume.fsversion',
'volume.is_partition',
'volume.disc.has_audio',
'volume.disc.is_appendable',
'org.freedesktop.Hal.Device.Volume.method_execpaths',
'volume.disc.is_rewritable',
'block.major',
'volume.uuid',
'volume.disc.type',
'org.freedesktop.Hal.Device.Volume.method_signatures',
'volume.label',
'volume.block_size',
'volume.disc.is_vcd']

class HalManager:
    def __init__(self):
        self.bus = dbus.SystemBus()
        self.manager_obj = self.bus.get_object('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager')
        self.manager = dbus.Interface(self.manager_obj, 'org.freedesktop.Hal.Manager')
        self.__initalize_lists()
        self.__get_devices()
        
    def __initalize_lists(self):
        self.cdDevices = {}
        self.props = []
        
    def __get_devices(self):
        # Initialize devices list
        self.__initalize_lists()
        #check for devices :)
        self.cd_udi_list = self.manager.FindDeviceByCapability('storage.cdrom')
        #get devices and propeties list
        for udi in self.cd_udi_list:
            vol_udi_list = self.manager.FindDeviceStringMatch ('info.parent', udi)
            for vol_udi in vol_udi_list:
                vol_obj = self.bus.get_object ('org.freedesktop.Hal', vol_udi)
                vol = dbus.Interface (vol_obj, 'org.freedesktop.Hal.Device')  
                self.cdDevices[vol.GetProperty('block.device')] = vol
                for prop in vol.GetAllProperties():
                    self.props.append(prop)

        self.__device_count = len(self.cdDevices)
        self.__initialized = True          

    def get_device_count(self):
        return self.__device_count
    
    def get_first_mounted_name (self):
        self.__get_devices()
        retName = ""
        for name, drive in self.cdDevices.iteritems():
            try:
                if drive.GetProperty('volume.is_mounted'):
                    retName = name
                    break
            except:
                pass
        return retName
    
    def is_empty(self, mountName = ""):
        self.__get_devices()
        if mountName != "":
            try:
                return self.cdDevices[mountName].GetPropety('volume.disc.has_data:')
            except:
                return False
        else:
            return True

    def get_first_mounted_point(self):
        self.__get_devices()
        retPointName = ""
        for name, drive in self.cdDevices.iteritems():
            if drive.GetProperty('volume.is_mounted'):
                retPointName = drive.GetProperty('volume.mount_point')
                break
        return retPointName.encode('utf8')
    
    def get_property(self,devicename ="", property_index = LABEL):
        if devicename !="":
            self.__get_devices()
            try:
                return self.cdDevices[devicename].GetProperty(device_properties[property_index])
            except:
                return "erro:", devicename, property_index
        else:
            return "" 