#!/usr/bin/python

#
# Copyright (c) 2007,2008,2009 MBARI
# MBARI Proprietary Information.  All Rights Reserved
#

import os
import commands

import tethysTimestamp
import utils
import config

from SlateRecord import SlateRecord

class Slate:

  # name of filename which will be passed to unserialize
  def __init__(self, unserializeBin, filename):
    self.unserializeBin = unserializeBin
    self.slatefile = filename 

  def read(self, *vars):

    records = []
    if not os.path.isfile(self.unserializeBin):
      return records

    # create the unserialize command
    cmd = self.unserializeBin
    cmd = cmd + " -h -c -o stdout "
    cmd = cmd + self.slatefile
    for i in vars:
      cmd = cmd + " " + i

    # run the command
    output = commands.getoutput(cmd)

    # get the data lines and delete the junk
    rawLines = output.splitlines()
    # clean the data
    rawLines = [ e for e in rawLines \
                if e.find("serialize") <= 0 \
                and e.find("Slate") <= 0 \
                and e.find("EpochSeconds") <= 0 ]

    # create the records
    records = [ [] for i in vars]
    for rawDataLine in rawLines:
      dataItems = rawDataLine.split(",")
      for i in range(len(vars)):
        # create the slate record
        t = tethysTimestamp.toDateTime(dataItems[0])
        rec = SlateRecord(t, dataItems[i + 2])
        records[i].append(rec) 
    return records

"""
# Example
s = Slate(config.UNSERIALIZE_BIN, config.SLATE_PATH)
(depths, latitudes) = s.read("depth", "latitude")
for depth in depths:
  print depth.timestamp, depth.data
"""
