#!/usr/bin/python

import os,sys
from fluents import dataset
import cfgparse, optparse
import re

PROGRAM_NAME = 'dataset'
VERSION = '0.1.0'

def read_dataset_header(input):
    name = ""
    type = ""
    dimensions = []

    kv_re = re.compile('^\s*#\s*(\w+)\s*:(.*)$')

    lines = []
    line = input.readline()
    while line.startswith('#'):
        lines.append(line)
        line = input.readline()

    for line in lines:
        match = kv_re.match(line)
        if not match:
            continue
        k, v = match.groups()
        k = k.strip()
        
        if k == 'name':
            name = v
        elif k == 'type':
            type = v
        elif k == 'dimension':
            values = v.split()
            dimensions.append((values[0], values[1:]))
    
    return (name, type, dimensions)

def show_info(input):
    name, type, dimensions = read_dataset_header(input)

    print "Name: %s" % name
    print "Type: %s" % type
    print "Dimensions:",
    for i, dim in enumerate(dimensions):
        dimname = dim[0]
        length = len(dim[1])
        print "%s(%i)" % (dimname, length),
        if i < len(dimensions)-1:
            print "x",
    print

def list_dimension_ids(input, dimname):
    name, type, dimensions = read_dataset_header(input)
    for i, dim in enumerate(dimensions):
        name, ids = dim
        if name == dimname:
            for id in ids:
                print id
            
def parse_options():
    conf_files = ['/etc/fluentsrc',
                  os.path.join(os.environ['HOME'], '.fluents')]

    cp = cfgparse.ConfigParser()
    op = optparse.OptionParser()

    op.add_option('-c', '--csv',
                  action='store_true', default=False,
                  help='Export as CSV file.')

    op.add_option('-d', '--dimension',
                  action='store', default=None,
                  help='Get all identifiers along a dimension.')

    op.add_option('-i', '--info',
                  action='store_true', default=False,
                  help='Show dataset information.')

    op.add_option('-l', '--longinfo',
                  action='store_true', default=False,
                  help='Display more information than -i.')

    op.add_option('-o', '--output-file',
                  action='store_true', default=False,
                  help='Send output to file instead of stdout.')

    op.add_option('-t', '--transpose',
                  action='store_true', default=False,
                  help='Transpose dataset.')

    op.add_option('-y', '--change-type',
                  action='store_true', default=False,
                  help='Set new dataset type.')


    for cf in conf_files:
        if os.path.isfile(cf):
            cp.add_file(cf)

    return cp.parse(op)

if __name__ == '__main__':
    options, params = parse_options()
    input = sys.stdin
    output = sys.stdout

    if options.info:
        show_info(input)
        sys.exit(0)

    elif options.dimension != None:
        list_dimension_ids(input, options.dimension)
    
