'''
Name: avi_dump_attribute_records.py

Overview: Generates an attribute dump for selected AVI feature class.

Description:
    This script will generate a Microsoft Word document containing the
    attributes for the selected AVI feature class. For each polygon the
    POLY_NUM is written then the overstory and understory records for the
    the polygon. 
    
Notes:

Author: Doug Crane
        Jan, 2010

Modifications:

'''

logChn = None

import pdb
import os
import sys
import datetime
import win32com.client

import arcpy

# General SRD utilities that may be needed.
from srd.srd_exception import *
import srd.srd_logging as srd_logging
import srd.srd_misc as srd_misc
import srd.srd_temp_ws as srd_temp_ws
import srd.srd_recordset as srd_recordset

from avi_record import *
from wordconstants import *

__author__ = 'Doug Crane'
__version__ = '1.0'

DEBUG = 1
# ====================================================================

if __name__ == '__main__':

    # Modify as required.
    arcpy.env.overwriteOutput = True
    # If using geographic features then may be best to modify these.
    arcpy.env.XYTolerance = .001
    arcpy.env.XYResolution = .0001
    arcpy.gp.logHistory = False

    if DEBUG:
        # Modify arguments to simulate those passed from toolbox.
        # You will have to modify these based on your scripts requirements.
        sys.argv = [sys.argv[0], \
        r'D:\testData\AVI\AVI_REC.gdb\avi_out']
        print('\n***\n*** IN DEBUG MODE\n***')
        arcpy.AddMessage('\n***\n*** IN DEBUG MODE\n***')
        
    try:
        logFilePath = srd_misc.getLogFilePath(sys.argv[0])
        logChn = srd_logging.SRD_Log(logFilePath)

        aviFCArg = arcpy.GetParameterAsText(0)

        #-------------------------------------------------------------
        # Set the log file.
        if logFilePath:
            # Parameters to tool will be written to log file in case of problems.
            params = arcpy.GetParameterInfo()
            hdrList = ['Arguments:']
            for param in params:
                hdrList.append('Name: %s, Type: %s, Value: %s' % (param.name, param.parameterType, param.value))
            
            logChn.stampHeader(hdrList)
            arcpy.AddMessage('\n*** Log information will be written to: %s\n' % logFilePath)

        # Ensure feature class exists before continuing.
        if not arcpy.Exists(aviFCArg):
            raise SRD_Exception('Feature Class: %s not found' % aviFCArg)

        # Obtain a dump of all records from the selected feature class.
        logChn.logMsg('\n*** Building attribute dump...')
        aviRecordObj = AVI_Record(aviFCArg)
        attDumpDict = aviRecordObj.buildAttributeDumpDict()

        # Need cerain constants to format Word document.
        wordConstantObj = microsoftWordConstants()

        # Create and opend a new Microsoft Word document.
        wordObj = win32com.client.Dispatch("Word.Application")
        wordDocObj = wordObj.Documents.Add()
        wordObj.Visible = True

        # Supress any error messages for grammar and spelling
        # since we know our record dumps are not traditional text.
        wordObj.ActiveDocument.GrammarChecked = True
        wordObj.ActiveDocument.SpellingChecked = True
        wordObj.ActiveDocument.ShowSpellingErrors = False
        wordObj.ActiveDocument.ShowGrammaticalErrors = False

        # Add some text.
        selectionObj = wordObj.Selection

        # Add Title information to our document.
        selectionObj.Font.Bold = 1
        selectionObj.Font.Size = 10
        selectionObj.Font.Name = "Arial"
        selectionObj.TypeText('AVI Attribute Dump\n')
        selectionObj.TypeText('Feature Class:\n')
        selectionObj.TypeText('\t%s\n' % aviFCArg)
        selectionObj.TypeText('Date: %s\n' % datetime.date.today())
        selectionObj.TypeText('Dump Produced By: %s\n' % os.environ.get('USERNAME'))
        selectionObj.TypeText('--------------------------------------------------------------------\n')
        selectionObj.InsertParagraph

        # Print out each record. We do not want to split records
        # accross page breaks so limit number of polygons printed per page.
        # Want a Courier font for equal spacing of records so record to
        # record comparisons is easier.

        # Number of polygons to print on first page.
        firstPageCnt = 15

        # Number of polygons to print on subsequent pages.
        pageCnt = 17
        
        selectionObj.Font.Bold = 0
        selectionObj.Font.Size = 8
        selectionObj.Font.Name = "Courier"

        # The attribute dump dictionary consists of each polygons
        # attributes formatted to a string and added to a list
        # containing each site type record. The dictionary key is
        # the POLYGON_ID of the polygon.
        firstPage = True
        recordCnt = 0
        for polygonID,siteRecords in attDumpDict.items():
            selectionObj.Font.Bold = 1
            selectionObj.TypeText('%s\n' % int(polygonID))
            selectionObj.Font.Bold = 0
            for siteRecord in siteRecords:
                selectionObj.TypeText('\t%s\n' % siteRecord)
            selectionObj.TypeText('---------------------------------------------------------------------------------------\n')

            # Determine is we need to insert a page break to
            # prevent splitting site records for a individual polygon.
            recordCnt += 1
            insertPageBreak = False
            if firstPage:
                if recordCnt >= firstPageCnt:
                    firstPage = False
                    insertPageBreak = True
                    recordCnt = 0
            else:
                if recordCnt >= pageCnt:
                    insertPageBreak = True
                    recordCnt = 0

            if insertPageBreak:
                selectionObj.InsertBreak(wordConstantObj.wdPageBreak)
                
    except SRD_Exception as e:
        if logChn:
            logChn.logError(e)
            logChn.logError(srd_misc.exceptionDetails(sys.exc_info()[2]))
        else:
            arcpy.AddMessage(srd_misc.exceptionDetails(sys.exc_info()[2]))
    except Exception as e:
        if logChn:
            logChn.logError(e)
            logChn.logError(srd_misc.exceptionDetails(sys.exc_info()[2]))
        else:
            arcpy.AddMessage(srd_misc.exceptionDetails(sys.exc_info()[2]))
    else:
        logChn.logMsg('\n*** %s completed normally\n' % sys.argv[0])
    finally:
        arcpy.ResetEnvironments()
                
