import time
import redis
import numpy as np
import json
import base64
import sys
#import neonIO
import time
from Queue import Queue
import sys
import numpy as np
import cStringIO
import random
class numpyEncoder(json.JSONEncoder):

    def default(self, obj):
        if isinstance(obj, np.ndarray):
            if obj.flags['C_CONTIGUOUS']:
                obj_data = obj.data
            else:
                cont_obj = np.ascontiguousarray(obj)
                assert(cont_obj.flags['C_CONTIGUOUS'])
                obj_data = cont_obj.data
            data_b64 = base64.b64encode(obj_data)
            return dict(__ndarray__=data_b64,
                        dtype=str(obj.dtype),
                        shape=obj.shape)
        return json.JSONEncoder(self, obj)

def numpyDecoder(obj):
    if isinstance(obj, dict) and '__ndarray__' in obj:
        data = base64.b64decode(obj['__ndarray__'])
        return np.frombuffer(data, obj['dtype']).reshape(obj['shape'])
    return obj

def jsonEncoder(array_data):
    return json.dumps(array_data, cls=numpyEncoder)

def jsonDecoder(json_data):
    _array=None
    try:
        _array=json.loads(json_data, object_hook=numpyDecoder)
        #_array=int(json.loads(json_data, object_hook=numpyDecoder))
    except:
        _array=None

    return _array

def list2json(list_data):
    return json.dumps(list_data)

def json2list(json_data):
    return json.loads(json_data)



ip="10.1.53.240"
port=9000
r=redis.Redis(host=ip, port=port, db=0)

#test sample
p1=r.get("/MR/workspace/sim/detector/module01/pid")
p2=r.get("/MR/workspace/sim/detector/module01/tof")
p3=r.get("/MR/workspace/sim/detector/module01/value")
#p4=r.get("/MR/workspace/sim/monitor01/value")
#pp=jsonDecoder(p4)
#print len(pp)
#print sum(pp[0])

tof=jsonDecoder(p2)
tof.append(60000)
_array=jsonDecoder(p3)
#_array_m=jsonDecoder(p4)
#print sum(pp)

    
CreateWorkspace(OutputWorkspace='sam',DataX=tof,DataY=_array, NSpec=6400,UnitX='TOF')
#CreateWorkspace(OutputWorkspace='monitor',DataX=tof,DataY=_array_m, NSpec=1,UnitX='TOF')
print "ok!"
LoadInstrument(Workspace="sam", Filename='/home/dur/work/online/mr/sim_online/instrument/detector.xml', RewriteSpectraMap='True')
#LoadInstrument(Workspace="monitor", Filename='/home/dur/work/online/mr/sim_online/instrument/monitor.xml', RewriteSpectraMap='True')
CloneWorkspace(InputWorkspace='sam',OutputWorkspace='ref_det_org')
ConvertUnits(InputWorkspace='ref_det_org',OutputWorkspace='ref_det_wave',Target='Wavelength', AlignBins=True)
CropWorkspace(InputWorkspace='ref_det_wave',OutputWorkspace='ref_det_ws',XMin=2.1,XMax=7.3)
#GroupDetectors(InputWorkspace='ref_det_wave', OutputWorkspace='ref_det_wave_group', DetectorList='10001-16400')
#ConvertUnits(InputWorkspace='ref_det_wave_group',OutputWorkspace='ref_det_group', Target='MomentumTransfer')
#Rebin(InputWorkspace='ref_det_group', OutputWorkspace='sample_Q_group', Params='0.1,0.001,0.6')

#monitor
LoadISISNexus(Filename='/home/dur/work/online/mr/sim_online/data/Sample_refl_D_0.3.nxs', OutputWorkspace='mon')
LoadInstrument(Workspace='mon', Filename='/home/dur/work/online/mr/sim_online/data/CSNS_REFL_Definition.xml', MonitorList='1', RewriteSpectraMap='False')
CropWorkspace(InputWorkspace='mon',OutputWorkspace='ref_mon_org',StartWorkspaceIndex='0',EndWorkspaceIndex='0')

#CloneWorkspace(InputWorkspace='monitor',OutputWorkspace='ref_mon_org')
ConvertUnits(InputWorkspace='ref_mon_org',OutputWorkspace='ref_mon_wave',Target='Wavelength', AlignBins=True)
RebinToWorkspace(WorkspaceToRebin='ref_mon_wave', WorkspaceToMatch='ref_det_ws', OutputWorkspace='ref_mon_ws')


# direct data

LoadISISNexus(Filename='/home/dur/work/online/mr/sim_online/data/Direct_D_0.3.nxs', OutputWorkspace='direct')
LoadInstrument(Workspace='direct', Filename='/home/dur/work/online/mr/sim_online/data/CSNS_REFL_Definition.xml', MonitorList='1', RewriteSpectraMap='False')
CropWorkspace(InputWorkspace='direct',OutputWorkspace='inc_detector_ws_orig',StartWorkspaceIndex='3',EndWorkspaceIndex='3')
CloneWorkspace(InputWorkspace='inc_detector_ws_orig',OutputWorkspace='inc_detector_ws_orig_corr')
MoveInstrumentComponent(Workspace='inc_detector_ws_orig_corr',ComponentName='point-detector',X='0.0',Z='21.475',RelativePosition='0')
ConvertUnits(InputWorkspace='inc_detector_ws_orig_corr',OutputWorkspace='inc_det_wave',Target='Wavelength')
CropWorkspace(InputWorkspace='direct',OutputWorkspace='inc_monitor',StartWorkspaceIndex='0',EndWorkspaceIndex='0')
ConvertUnits(InputWorkspace='inc_monitor',OutputWorkspace='inc_mon_wave',Target='Wavelength')


Divide(LHSWorkspace='ref_det_ws',RHSWorkspace='ref_mon_ws',OutputWorkspace='ref_result')
#deal with direct
RebinToWorkspace(WorkspaceToRebin='inc_mon_wave', WorkspaceToMatch='ref_det_ws', OutputWorkspace='inc_mon_ws')
RebinToWorkspace(WorkspaceToRebin='inc_det_wave', WorkspaceToMatch='ref_det_ws', OutputWorkspace='inc_det_ws')
Divide(LHSWorkspace='inc_det_ws',RHSWorkspace='inc_mon_ws',OutputWorkspace='inc_result')
#correction with direct
Divide(LHSWorkspace='ref_result',RHSWorkspace='inc_result',OutputWorkspace='IvsLam')
#convert to Q
ConvertUnits(InputWorkspace='IvsLam', OutputWorkspace='IvsQ_reduce', Target='MomentumTransfer', AlignBins=True)
GroupDetectors(InputWorkspace='IvsQ_reduce', OutputWorkspace='sample_Q', DetectorList='10001-16400')



