#
# This program reads the storage objects from Redis and
# generates a csv file with all the data
#
import redis, os, csv

COLS_2 = [
        'DATE', 'SYSTEM_SERIALNO', 'CHASSIS_SERIALNO', 'HOSTNAME',
        'VERSION', 'LOCATION', 'MODEL_NO', 'Pre:Used',
        'Post:Used', 'Post:Size', 'UPTIME', 'GENERATED_EPOCH_TIME',
        'GENERATED_ON', 'TIME_ZONE', 'ADMIN_EMAIL'
        ]


def write_single_serialno(writer, datestr, serialno, rds):
    name = 'extract:' + datestr + ':' + serialno
    d_params = rds.hgetall(name)
    writer.writerow(d_params)

def generate_csv(dirname, datestr):
    rds = redis.StrictRedis(host='localhost', port=6379, db=0)
    base = 'extract:' + datestr
    serial_count = 0
    filename = 'storage_' + datestr + '.csv'
    abs_file = dirname + '/' + filename
    with open(abs_file, 'w') as fp:
        serialset = rds.smembers(base)
        writer = csv.DictWriter(fp, fieldnames=COLS_2)
        writer.writeheader()
        for serialno in serialset:
            write_single_serialno(writer, datestr, serialno, rds)
            serial_count += 1
    return serial_count


if __name__ == "__main__":
    print 'In serialize.py'
    s_count = generate_csv('output', '2016-07-21')
    print 'csv created, serial number count: ' + str(s_count)
