"""
Manipulating the leak detector logs.
"""

import os
import os.path
import time
import datetime
import numpy
import matplotlib.dates
import flib
import timelog
import ascii2numpy

class LDLog(timelog.TimeLog):
    """
    Represents a leak detector log over a certain time.
    Two logs can be concatenated with a '&' sign

    log format:
    1  [:,0]  Time (sec, since 00:00 1 January 1970 GMT)
    2  [:,1]  LR [mbar*l/sec]
    """

    @staticmethod
    def fieldcount(): "return number of columns in the self.data"; return 2
    
    def LR(self): "leak rate [mbar*l/sec]"; return self.data[:,1]

    def __repr__(self): return "LDLog %s" % (self.datespan())

    @staticmethod
    def load(filename):
        """
        Load leak detectorlog from a given file
        The function determines file format from the date:
            1: modern format, since 21 December 2008
            2: old format, does not contain absolute time. winter/summer time changes are not handled correctly.
        """
        basename = os.path.basename(filename)
        
        data = ascii2numpy.loadascii(filename, cols=2)
        data[:,0] = flib.labview2tm(data[:,0])
            
        return LDLog(data)
    
    @staticmethod
    def loadrun(run, start = None, end = None):
        """
        Return log for a given run, withing [start, end] period if boundaries are specified.
        """
        logdir = flib.smbpath('/mnt/phpc338/run%d/LD' % run)
        return LDLog.loaddir(logdir, start=start, end=end).period(start, end)
