#
#
# WYWOLANIE:
#
# python "C:\python25\select.py" --table="TABLE_NAME" --attr="ATTR_NAME" --output="OUTPUT_FILE_NAME"
#
#
#

import sys

import os

import getopt


sys.path.append("c:\\GRASS\etc\\python")

import grass.script as grass


def get_attr(table, attr, output):
        
        print attr
        print table
        print output

        FILE = open('tmp.txt', 'w')

        FILE.write('SELECT ' + attr + ' FROM ' + table)

        FILE.close()

        data = grass.parse_command('db.select', input = 'tmp.txt')                            

        FILE = open(output, 'w')

        for item in data:
             FILE.write(item + '\r')
             
        FILE.close()
        


def main(argv):

       

    try:  
        opt, args = getopt.getopt(argv, "ht:a:o:", ["help", "table=", "attr=", "output="])

    except:
        usage()
        sys.exit(2)

   
    outputs = ''
    tables = ''
    attrs = ''


    
    #Loop through all the option / argument pairs and perform any actions associated with them.

    for o, a in opt:
        if o in ("-h", "--help"):
            usage()
            sys.exit()
        elif o in ("-a", "--attr"):
            attrs = a
        elif o in ("-t", "--table"):
            tables = a
        elif o in ("-o", "--output"):
            outputs = a
        else:
            assert False, "unhandled option"

    grass.parse_command('g.remove', vect = 'firestations_cp')

    grass.parse_command('g.copy', vect = 'firestations,firestations_cp')

    grass.parse_command('db.connect', driver = 'dbf', database='$GISDBASE/$LOCATION_NAME/$MAPSET/dbf/')

    get_attr(tables, attrs, outputs)



    
if __name__ == "__main__":
    main(sys.argv[1:])

