'''
Name: srd_temp_ws.py

Overview: 

Description:
    
    
Notes:

Author: Doug Crane
        May, 2012

Modifications:

'''

__author__ = 'Doug Crane'
__version__ = '1.0'

import sys
import os

import arcpy

import srd_featureclass_info
import srd_misc
import srd_logging
from srd_exception import *

__all__ = ['SRD_TempWS']

# ====================================================================
class SRD_TempWS(object):

    # By default prefix for temp workspace will be as follows.
    DEFAULT_WS_PREFIX = 'tmp_ws'
    
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def __init__(self, fgdbPrefix=None, tmpPath=None):
        '''
        Creates a temporary file geodatabase

        Creating an instance of this class will create an FGDB using
        the fgdbPrefix you provided. The directory where this FGDB is
        created depends on whether or nor you included a value for the
        useSameFeatureClassDir parameter. If you passed an existing
        feature class using this parameter then the temp FGDB will be
        created in this directory. If not feature class is passed then
        the environment variable TEMP is used to determine the directory.

        If an FGDB with the name generated from the fgdbPrefix already
        exists then a unique FGDB name will be generated by adding a
        number to end of fgdbPrefix. For example, if you passed the prefix
        tmpfgdb and there is already an FGDB with this name then the new
        FGDB will be given the name tmpfgdb0 or tmpfgdb1, etc...
        
        Parameters:

            Optional:

            fgdbPrefix - prefix to use to identity the temporary
                         file geodatabase. Defaults to tmp_ws

            tmpPath - directory to where to create temporary FGDB.
                      If tmpPath is an existing feature class then
                      the temp WS will be placed in the parent directory
                      of this feature class.
            
        Variables:
            FGDBPath - full path to temporary FGDB that was created.
            FGDBName - name of FGDB with no path information.
            parentDir - parent directory containing the FGDB
            fgdbPrefix - prefix used to designate the workspace.

        Examples:
        
        '''
        
        self.parentDir = ''
        self.FGDBName = ''
        self.FGDBPath = ''
        if fgdbPrefix:
            self.fgdbPrefix = fgdbPrefix
        else:
            self.fgdbPrefix = SRD_TempWS.DEFAULT_WS_PREFIX

        self._logChn = srd_logging.SRD_Log()
        
        # If user wants temp FGDB in same directory as another feature
        # class then get its parent directory.

        if tmpPath:
            if not arcpy.Exists(tmpPath):
                raise SRD_Exception('Temp Path: %s does not exist' % tmpPath)

            # tmpPath may be an actual directory or path to existing feature class.
            if os.path.isdir(tmpPath):
                self.parentDir = tmpPath
            else:
                # Assume the tmpPath is a path to an existing feature class.
                utilFC = srd_featureclass_info.SRD_FeatureClassInfo(tmpPath)
                utilFC.getParentDir()
                basePath = utilFC.parentDir
                self.parentDir = utilFC.parentDir                
        else:
            self.parentDir = r'c:\_LocalData'
            if not os.path.exists(self.parentDir):
                self.parentDir = arcpy.env.scratchFolder

        # Failed to determine type so exit with error.
        if not self.parentDir:
            raise SRD_Exception('__init__: Unable to obtain directory to create temporary FGDB in')
        
        # We should have the directory where FGDB is to be created.
        if not os.path.exists(self.parentDir):
            raise SRD_Exception('__init__: Directory to create temp FGDB does not exist: %s' % self.parentDir)
        
        # Generate a unique name for the FGDB.
        self.FGDBPath = arcpy.CreateUniqueName(self.fgdbPrefix+'.gdb', self.parentDir)

        # Need name without path for FGDB creation.
        self.FGDBName = os.path.basename(self.FGDBPath)
        arcpy.CreateFileGDB_management(self.parentDir, self.FGDBName)
        self._logChn.logMsg('*** Created Temp WS: %s' % self.FGDBPath)
        
        # Perform refresh to ensure visibility.
        arcpy.RefreshCatalog(self.parentDir)

    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def getTempPath(self, featureClassName):
        '''
        Returns the full path of feature class that will be created
        within the temp FGDB. Use this to get a full path to a
        feature class that you want to use with geoprocessing commands
        that are expecting a full path value.

        Parameters:
            featureClassName - name of feature class that will be
                               used to generate full path.

        Example:
            tmpFGDB.getTempPath('tmp_int')
            
        '''

        return os.path.join(self.FGDBPath, featureClassName)
        
    # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    def deleteAllTempWS(self, fgdbPrefix=None):
        '''
        Deletes all existing FGDBs found in the parent directory
        of the current temp FGDB. Only call if you have completed
        using the current instance of a temp FGDB.

        Call this method when you may have failed to delete previous
        instances of your temporary FGDBs and you wish to remove all
        FGDBs that start with the given fgdbPrefix.

        Note:
        Be carefull using this method when you are using multiple instances
        of the class with the same FGDB prefix. You may end up deleting
        an FGDB you are still working with if you use this method.

        Parameters:
            fgdbPrefix - prefix used to create temp WS. If not passed
                         then default WS prefix is used.
        '''

        # Assume the default workspace prefix is intended.
        if not fgdbPrefix:
            fgdbPrefix = SRD_TempWS.DEFAULT_WS_PREFIX
            
        # Temporary FGDBs are created using the prefix and
        # appending a sequential number that will make it unique
        # within the parent directory. Look for any FGDBs like this
        # and delete them if found.
        if self.parentDir:
            tmpFGDBPath = os.path.join(self.parentDir, fgdbPrefix)
            if os.path.exists(self.parentDir):
                for i in range(0,100):
                    delFGDBPath = tmpFGDBPath + str(i) + '.gdb'
                    if arcpy.Exists(delFGDBPath):
                        try:
                            arcpy.Delete_management(delFGDBPath)
                            self._logChn.logMsg('Deleted %s' % delFGDBPath)
                        except:
                            self._logChn.logMsg('Cannot delete %s' % delFGDBPath)

                # Check for one that has no suffix number.
                delFGDBPath = tmpFGDBPath + '.gdb'
                if arcpy.Exists(delFGDBPath):
                    try:
                        arcpy.Delete_management(delFGDBPath)
                        self._logChn.logMsg('Deleted %s' % delFGDBPath)
                    except:
                        self._logChn.logMsg('Cannot delete %s' % delFGDBPath)
                        
                arcpy.RefreshCatalog(self.parentDir)

# --------------------------------------------------------------------
if __name__ == '__main__':

    try:

        featureClass = r'D:\testData\myMdbTest.mdb\TILE10'

        myObj = SRD_TempWS('tmp_wrk', featureClass)

        myObj.deleteAllTempWS('tmp_wrk')

        myObj = SRD_TempWS('tmp_wrk', r'd:\tmp')

        myObj.deleteAllTempWS('tmp_wrk')

        myObj = SRD_TempWS()
        myObj.deleteAllTempWS()
        
    except SRD_Exception as e:
        print e.errMsg
        arcpy.AddError(e.errMsg)
