import traceback

is_panel = False #get_exec_pars().source != CommandSource.ui  #Must be checked before callin "run"

#set_exec_pars(provider="txt")

BPM_SENSORS = [("x","X1"), ("y","Y1"), ("q","Q1")] #(logic name sufix, channel sufix)

#Paramter parsing
prefix     = args[0] if is_panel else "S30CB09-DWSC440"  #"SINDI01-DWSC090" 
scan_type  = args[1] if is_panel else "X1"
scan_range = args[2] if is_panel else [-200, 200, -200, 200]
cycles     = args[3] if is_panel else 1
velocity   = args[4] if is_panel else 400
bpms       = args[5] if is_panel else ["BPM1", "BPM2"]
blms       = args[6] if is_panel else ["BLM1", "BLM2"]
bkgrd      = args[7] if is_panel else 10
plt        = args[8] if is_panel else plot(None, title = "Wire Scan")[0]
save_raw   = args[9] if is_panel else False
do_elog    = False if (plt is None) else (True    if is_panel else False)
print "WireScan parameters: ", prefix, scan_type, scan_range, cycles, velocity, bpms, blms, bkgrd

print "---"
print get_exec_pars().source
print is_panel
print plt 

#Plot setup
if plt is not None:
    plt.clear()
    plt.removeMarker(None)
    plt.getAxis(plt.AxisId.X).setLabel("Position");
    plt.getAxis(plt.AxisId.Y).setLabel("");
    plt.getAxis(plt.AxisId.Y2).setLabel("");
    plt.setLegendVisible(True);       
snapshots = []

#Creating WireScanner object
print "Creating scanner..."
scanner = DummyPositioner("scanner")


class Sensor(ReadonlyRegisterBase):  
    def __init__(self, name):
        ReadonlyRegisterBase.__init__(self, name)
        self.index = -1
        self.initialize()
        
    def doRead(self):
        self.index +=1
        return float(self.index)


#Lis of stream channels
channels = [Sensor("m_pos"), 
            Sensor("cur_cycle"),
            Sensor("scanning")]                
for i in range (len(blms)):
    channels.append (Sensor("blm" + str(i+1)))
    if plt is not None:
        series = LinePlotSeries(blms[i], None, min(i+1, 2))
        plt.addSeries(series)     
        series.setLinesVisible(False)
        series.setPointSize(2)
    if save_raw:    
        channels.append (Sensor("blm" + str(i+1) + "_raw"))
for i in range (len(bpms)):
    for sensor in BPM_SENSORS:
        channels.append (Sensor("bpm" + str(i+1) + "_" + sensor[0]))
    
#Metadata
print "1"
set_attribute("/", "Wire Scanner", prefix)    
set_attribute("/", "Scan Type", scan_type)    
set_attribute("/", "Range", scan_range)    
set_attribute("/", "Cycles", cycles)    
set_attribute("/", "Motor Velocity", velocity*math.sqrt(2))  
set_attribute("/", "Wire Velocity", velocity)
set_attribute("/", "Background Measures", bkgrd)
set_attribute("/", "BPMs", bpms)
set_attribute("/", "BLMs", blms)
print "2"
filename = get_exec_pars().path



class Timestamp(Readable):
    def read(self):        
        return time.time()

        


#End of  scan checking
scan_complete, cur_cycle, wire = None, None, None

def check_end_scan(record, scan):
    global scan_complete,cur_cycle
    if record[4]<1:
        print "Data aquisition completed"
        scan_complete=True
        scan.abort()
        record.cancel() #So it won't be saved
    else:
        position = record[0]
        if record[3] != cur_cycle:
            cur_cycle = record[3]
            get_context().dataManager.splitScanData(scan)
            #if plt is not None: for s in plt.getAllSeries(): s.clear()
        if plt is not None:    
            for i in range (len(blms)):
                plt.getSeries(i).appendData(position, record[5 + i])                

#Process background
def do_background():
    #Store Background
    if bkgrd>0:

        set_exec_pars(group = "background")
        #r = tscan ( channels, bkgrd, 0.01, group = "background")    
        r = tscan ( channels, bkgrd, 0.01) 
        print "BACKGROUND..."
        for i in range(len(r.getReadables())):
            d = r.getReadable(i)              
            path = get_exec_pars().group + r.getReadables()[i].name
            print path
            set_attribute(path, "Mean", mean(d))            
            set_attribute(path, "Sigma", stdev(d) )       
        print "DONE"                         

#Scan   
def do_scan(index):    
    global scan_complete, cur_cycle, wire
    wire = "y" if (index==1) or (scan_type in ["Y1", "Y2"]) else "x"
                

    if plt is not None:
        if wire == "x":
            plt.getAxis(plt.AxisId.X).setRange(scan_range[0], scan_range[1])        
        else:
            plt.getAxis(plt.AxisId.X).setRange(scan_range[2], scan_range[3])
    

    scan_complete=False
    cur_cycle = 1.0

    if plt is not None:
        for s in plt.getAllSeries():
            s.clear()
        plt.removeMarker(None)
    try:         

        #TODO: Check what the problem is
        #mscan (st, [w_pos(),] + st.getReadables() + [Timestamp(),], -1, -1, take_initial = True, after_read = check_end_scan)                           

        l=[Sensor("w_pos")] ; l.extend(channels); l.append(Timestamp())
        #mscan (st, l, -1, -1, take_initial = True, after_read = check_end_scan)                           
        
        #tscan([w_pos()] + getReadables() + [Timestamp(),], 10, 0.5)
        for i in range(cycles):
            #set_exec_pars(group=wire+"_{count}", reset=(i==0))    
            tscan(l, 10, 0.5, group=wire+"_{count}", reset=(i==0))
            #tscan(l, 10, 0.5)
    except:        
        print sys.exc_info()[1]

        if not scan_complete:
            raise
    finally:        
        #Combining data of multiple series
        #s=plt.getSeries(0)
        #indexes = sorted(range(len(s.x)),key=lambda x:s.x[x])
        #x,y = [s.x[x] for x in indexes], [s.y[x] for x in indexes]
        #plot(y, xdata = x)          
        calculate()        
        img_file = os.path.abspath(filename + "_" + get_exec_pars().group[0:1] + ".png")
        time.sleep(0.1) #Give some time to plot finish (async)
        if plt is not None:
            plt.saveSnapshot(img_file, "png")
            snapshots.append(img_file)     

msg = ""
ret = []
def calculate():
    global msg
    stats = []
    for i in range(len(blms)):
        msg += "Wire " + wire + "  -  BLM " + str(i+1) + ":\n"
        try:          
            bg = get_attributes("background/blm" + str(i+1))["Mean"] if bkgrd>0 else 0.0
            samples = [[], [], [], []]   
            for cycle in range (cycles):   
                pos_path = wire+"_" + ("%04d" % (cycle+1)) + "/w_pos"
                pos = load_data(pos_path)
                path = wire+"_" + ("%04d" % (cycle+1)) + "/blm" + str(i+1)
                data = load_data(path)         
                sp = data #blm_remove_spikes(data)
                sig = sp if bg is None else [v-bg for v in sp]   
                
                rms_com, rms_sigma = [10.0, 20.0] #[profile_rms_stats(pos, sig,noise_std=0, n_sigma=3.5)
                set_attribute(path, "RMS COM", float("nan") if (rms_com is None) else rms_com)            
                set_attribute(path, "RMS Sigma", float("nan") if (rms_sigma is None) else  rms_sigma)            
                
                #print [com, rms]
                [off, amp, com, sigma] = [30.0, 40.0, 50.0, 60.0] #profile_gauss_stats(pos, sig, off=None, amp=None, com=None, sigma=None)
                set_attribute(path, "Gauss COM", float("nan") if (com is None) else com)            
                set_attribute(path, "Gauss Sigma", float("nan") if (sigma is None) else sigma)                                            
        
                samples[0].append(rms_com);samples[1].append(rms_sigma);samples[2].append(com);samples[3].append(sigma)
                print get_exec_pars().path + " | "+ path
                ret.append([rms_com, rms_sigma, com, sigma, get_exec_pars().path + "|"+ pos_path,  get_exec_pars().path + "|"+ path])
                #print [off, amp, com, sigma]
        
                #from mathutils import Gaussian
                #g = Gaussian(amp, com, sigma)
                #gauss = [g.value(v)+off for v in pos]
                #plot([data, sp, sig, gauss], ["data", "sp", "signal", "gauss", ], xdata = pos, title="Fit blm" + str(i+1) + " - " + str(cycle+1))           
            print "X" 
            stats.append([])
            for sample in samples:
                sample =  [v for v in sample if v is not None]
                stats[i].append( (mean(sample), stdev(sample)) if len(sample)>0 else (float("nan"), float("nan")) )
            if plt is not None:    
                plt.addMarker(stats[i][2][0], None, "Gcom=" + "%.2f" % stats[i][2][0], plt.getSeries(i).color)
                plt.addMarker(stats[i][0][0], None, "Rcom=" + "%.2f" % stats[i][0][0], plt.getSeries(i).color.brighter())
                
            msg += "    RMS COM: " + "%.4f" % stats[i][0][0]  +  " +- " +"%.4f" % stats[i][0][1] + "\n"  #unichr(0x03C3) + "="
            msg += "    RMS Sigma: " + "%.4f" % stats[i][1][0]  +  " +- " + "%.4f" % stats[i][1][1] + "\n"
            msg += "    Gauss COM: " + "%.4f" % stats[i][2][0]  + " +- " + "%.4f" % stats[i][2][1] + "\n"
            msg += "    Gauss Sigma: " + "%.4f" % stats[i][3][0]  +  " +- " + "%.4f" % stats[i][3][1] + "\n"

        except Exception, e:
            print >> sys.stderr, traceback.format_exc()
            msg += str(e)+ "\n"
                        

print "Starting scan..."         
try:     
    do_background()       
    do_scan(0)
    if scan_type in ["Set1", "Set2"]:        
        do_scan(1)                             
finally:
    print "Closing scanner"

    print "Closing stream"
    
           
print msg

# save the entry in the logbook
if do_elog:
    if get_option("Generated data file:\n" + filename +"\n\n" + msg + "\n\n" + "Save to ELOG?", "YesNo") == "Yes":    
        log_msg = "Data file: " + filename
        log_msg = log_msg + "\nWire Scanner: " + prefix
        log_msg = log_msg + "\nScan Type: " + str(scan_type)
        log_msg = log_msg + "\nRange: " + str(scan_range)
        log_msg = log_msg + "\nCycles: " + str(cycles)
        log_msg = log_msg + "\nWire Velocity: " + str(velocity)
        log_msg = log_msg + "\nBackground Measures: " + str(bkgrd)
        log_msg = log_msg + "\nBPMs: " + str(bpms)
        log_msg = log_msg + "\nBLMs: " + str(blms)
        
        log_msg = log_msg + "\n" + msg
        elog("Wire Scan", log_msg, snapshots)


set_exec_pars(open=False)
set_return(ret)
