import nds2
import numpy
import os
from pylab import *
import time
#from scipy.signal import cheby1, firwin, lfilter
from scipy.signal import cheby1, lfilter

def gps2str(gps, zone='utc'):
    if (zone == 'utc'):
        tz = time.mktime(time.gmtime()) - time.mktime(time.localtime())
        return time.ctime(gps + 315964785 + tz) + ' UTC'
    else:
        return time.ctime(gps + 315964785)

def gps_now():
    """Return the actual GPS time."""
    return int(time.time() - 315964785)


def cohe_color(c):
    """Return an hex color code depending continuosly
    on input: 1 = red, 0 = white
    """
    if c == 0:
        return '#ffffff'
    else:
        if c == 1:
            return '#ff0000'
        else:
            s = hex(int((1.0 - c) * 256)).split('x')[1]
            if len(s) == 1:
                s = '0' + s
            return '#ff' + s + s

# Function to get data from raw
def getRawData(ch, gps, dt):
    """Read data from RAW file:
    ch  = channel name
    gps = gps time
    dt  = duration
    """
    try:
        str1 = nap.FrameIChannel('/virgoData/ffl/raw.ffl', ch, dt, gps)
        d = nap.SeqViewDouble()
        str1.GetData(d)
        fs = 1.0 / d.GetSampling()
        return d.row(0), fs
    except:
        print "Error reading channel %s at gps %d + %d" % (ch, gps, dt)
        return -1


def decimate(x, q, n=None, ftype='iir', axis=-1):
    """downsample the signal x by an integer factor q, using an order n filter
    
    By default, an order 8 Chebyshev type I filter is used or a 30 point FIR 
    filter with hamming window if ftype is 'fir'.

    (port to python of the GNU Octave function decimate.)

    Inputs:
        x -- the signal to be downsampled (N-dimensional array)
        q -- the downsampling factor
        n -- order of the filter (1 less than the length of the filter for a
             'fir' filter)
        ftype -- type of the filter; can be 'iir' or 'fir'
        axis -- the axis along which the filter should be applied
    
    Outputs:
        y -- the downsampled signal

    """

    if type(q) != type(1):
        raise Error, "q should be an integer"

    if n is None:
        if ftype == 'fir':
            n = 30
        else:
            n = 4
    if ftype == 'fir':
        b = firwin(n+1, 1./q, window='hamming')
        y = lfilter(b, 1., x, axis=axis)
    else:
        (b, a) = cheby1(n, 0.05, 0.8/q)

        y = lfilter(b, a, x, axis=axis)

    return y.swapaxes(0,axis)[::q].swapaxes(0,axis)

def newline_name(s):
    if len(s) > 10:
        N = len(s)/10
        idx = []
        for i in range(N):
            try:
                idx.append(s.index('_', 10*(i+1)))
            except:
                pass
        if len(idx) !=0:
            newstr = ''
            for i in range(len(idx)):
                if i == 0: 
                    newstr = s[0:idx[0]]
                else:
                    newstr = newstr + "<br>" + s[idx[i-1]:idx[i]]
            newstr = newstr + '<br>' + s[idx[-1]:]
            return newstr
        else:
            return s
    else:
        return s

