import ch.psi.pshell.imaging.ImageBuffer as ImageBuffer
import json
import ch.psi.pshell.bs.PipelineServer as PipelineServer
import ch.psi.pshell.imaging.Colormap as Colormap


if get_exec_pars().source == CommandSource.ui:
    #camera_name = "SARBD02-DSCR050" # "SLG-LCAM-C041_sp"
    #camera_name = "SARBD02-DSCR050_sp" # "SLG-LCAM-C041_sp"
    camera_name = "simulation_sp" # "SLG-LCAM-C041_sp"    
    shared = False
    images = 1
    interval = -1
    roi = ""
    #roi = "[300, 200]"
    #roi = "[540, 200, 430,100]"
    snapshot = False
else:    
    camera_name = args[0]
    shared = args[1].lower() == "true"
    images = int(args[2]) if len(args)>2 else 1
    interval = int(args[3]) if len(args)>3 else -1
    roi = args[4] if len(args)>4 else ""
    snapshot = args[5].lower() == "true" if len(args)>5 else False


background = get_exec_pars().background 


run("Tools/CameraTools")        
set_exec_pars(name="camera_data")

if background:    
    _server = PipelineServer("pipeline_server", cam_server.url)
    _server.config.colormap = Colormap.Flame
    _server.config.colormapAutomatic = True    
    _server.initialize()
else:
    _server = cam_server

try:
    _server.start(camera_name + "_sp1" if shared else camera_name, shared)
      
    if roi is not None and len(roi.strip())>0:
        roi = json.loads(roi)   
        if len(roi) == 2:
        
            if _server.stream.take() == None:
                _server.waitNext(10000)           
            while True:
                if json.loads(_server.stream.take()["processing_parameters"])["image_region_of_interest"] == None: 
                    break
                _server.resetRoi()
                _server.waitNext(10000)                                  
            iw, ih, cx, cy = _server.getValue("width"), _server.getValue("height"), _server.getValue("x_fit_mean"), _server.getValue("y_fit_mean")
            xa, ya = _server.getValue("x_axis"), _server.getValue("y_axis") 
            cx  = (cx - xa[0]) / (xa[-1]-xa[0]) * iw
            cy  = (cy - ya[0]) / (ya[-1]-ya[0]) * ih
            w, h = roi[0], roi[1]
            x, y = int(max(cx- (w/2), 0)), int(max(cy-(h/2), 0))
            w, h = min(w, iw-x), min(h, ih-y)        
            roi = [x, w, y, h]
            if (w<0) or (h<0):
                raise Exception("Invalid ROI: " + str(roi))
            _server.setRoi(roi[0], roi[2], roi[1], roi[3])    
        elif len(roi) == 4: 
            _server.setRoi(roi[0], roi[2], roi[1], roi[3])    
        else:
            raise Exception("Invalid ROI: " + str(roi))
        while True:        
            _server.waitNext(10000)
            r = json.loads(_server.stream.take()["processing_parameters"])
            if  roi == r["image_region_of_interest"]:
                break;
    else:
        _server.waitNext(10000)

    
    data_file = save_camera_data(_server, images, interval, parallel = True, pause=True)    
    set_exec_pars(open = False)
    
    if snapshot:
        format ="png"
        save_camera_snapshot(_server, data_file + "." + format, format)
finally:    
    if background:
        _server.close()
    else:
        _server.stop()

set_return(data_file)
