# 
# CastPodder miscellaneous methods
# Copyright (c) 2005-2006 Scott Grayban and the CastPodder Team
#
# 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
#
# $Id: misc.py 96 2006-07-10 19:50:46Z sgrayban $

import os
import logging
import time

try: 
    import win32api
except ImportError: 
    win32api = None
    
log = logging.getLogger('iPodder')

def freespace(path): 
    "Return free disk space in MB for the requested path; -1 if unknown."
    if win32api is not None: 
        cwd = os.getcwd()
        try: 
            os.chdir(path)
            sps, bps, freeclusters, clusters = win32api.GetDiskFreeSpace()
            return sps * bps * freeclusters
        finally: 
            os.chdir(cwd)
    else:
        # These three lines could probably replace all of this?
        import statvfs
        stats = os.statvfs(path)
        return stats[statvfs.F_BAVAIL] * stats[statvfs.F_BSIZE]

    if not freespace.warned: 
        freespace.warned = True
        log.warn("Can't determine free disk space.")
    return -1
    
freespace.warned = False

def rename(old,new,backup=False):
    """Like os.rename, but first clears the new path so Windows
    won't throw Errno 17.  Optionally backs up the new location
    if something is there."""
    if not os.path.exists(old):
        raise Exception, "File %s doesn't exist" % old
    try:
        if backup:
            os.rename(new,"%s-%d" % (new,int(time.time())))
        else:
            os.remove(new)
    except OSError, ex:
        errno, message = ex.args
        if errno != 2: # ENOFILE
            raise OSError, ex

    os.rename(old,new)
