# ---------------------------------------------------------------------------
# UniqueValToDomain.py
# Created on: 2012-11-06 10:18:49.00000
#   (generated by ArcGIS/ModelBuilder)
# Usage: UniqueValToDomain <Workspace> <Table> <Frequency_Field_s_> <Field_Name> <Domain_Update_Option> <Domain_Name>
# Description:
# ---------------------------------------------------------------------------

# Set the necessary product code
# import arcinfo


# Import arcpy module
import arcpy

def FindField(Table, FieldName):
    dsc = arcpy.Describe(Table)
    returnField = None
    for field in dsc.fields:
        #arcpy.AddMessage('Comparing field name {0} to input {1}'.format((str.upper(str(field.Name))), str.upper(FieldName)))
        if str.upper(str(field.Name)) == str.upper(FieldName):
            returnField = field
            #arcpy.AddMessage('Found the field')
            break
    return returnField

def UniqueValueToDomain(Workspace, Table, Field_Name, Domain_Name):
    arcpy.env.overwriteOutput = True
    tempFRQTable = 'IN_MEMORY/FRQ'
    tempFRQView = "frq_View"
    
    InputField = FindField(Table, str(Field_Name))
    #arcpy.AddMessage(InputField.type)
    if (InputField.type in [u'SmallInteger', u'Double', u'Long', u'OID', u'Single', u'Integer']):
        notEmptySQL = """"Code" IS NULL"""
    else:
        notEmptySQL = """"Code" IS NULL OR "Code" = ''"""

	# Process: Frequency
    arcpy.Frequency_analysis(Table, tempFRQTable, Field_Name)


    # Process: AddField
    arcpy.AddField_management(tempFRQTable, "Description", "TEXT")
    arcpy.AddField_management(tempFRQTable, "Code", InputField.type, InputField.precision, InputField.scale, InputField.length)

    # Process: CalculateField
    arcpy.CalculateField_management(tempFRQTable, "Description", "[" + Field_Name + "]", "VB", "")
    arcpy.CalculateField_management(tempFRQTable, "Code", "[" + Field_Name + "]", "VB", "")

    #Delete empty codes
    arcpy.MakeTableView_management(tempFRQTable,tempFRQView)
    arcpy.SelectLayerByAttribute_management(tempFRQView,"NEW_SELECTION",notEmptySQL)
    arcpy.DeleteRows_management(tempFRQView)

    # Process: TableToDomain
    arcpy.TableToDomain_management(tempFRQView, "Code", "Description", Workspace, Domain_Name, "Description", "REPLACE")

    # Process: AssignDomainToField
    arcpy.AssignDomainToField_management(Table, Field_Name, Domain_Name)


if __name__ == '__main__':
    # Script arguments
    Workspace = arcpy.GetParameterAsText(0)
    Table = arcpy.GetParameterAsText(1)
    Field_Name = arcpy.GetParameterAsText(2)
    Domain_Name = arcpy.GetParameterAsText(3)

    ##Workspace = "E:/GIS_DATA/LADOT/LADOT@local.sde"
    ##Table = "E:/GIS_DATA/LADOT/LADOT@local.sde/LADOT.DBO.Federal_Aid_Sys_Trav"
    ##Field_Name = "FED_AID_SYS_TRAV"
    ##Domain_Name = "dFED_AID_SYS_TRAV"

    UniqueValueToDomain(Workspace, Table, Field_Name, Domain_Name)

