import numpy
import config
import SimpleITK
import os
import getData

def guessPixelPosition15(sx=-1,sy=-1,sz=-1):
    #guess position of segments
    if sx<0:
        sx=12
    if sy<0:
        sy=28
    if sz<0:
        sz=32
    rz=4
    oz=0

    slc=[sx,sy,sz]
    p1=[sx,sy,sz]
    pts={
      '0':[sx-5,sy,sz],\
      '1':[sx-2,sy,sz-rz],\
      '2':[sx-2,sy,sz+rz-1],\
      '3':[sx-1,sy-rz,sz],\
      '4':[sx-1,sy+rz-1,sz],\
      '5':[sx,sy-rz+oz,sz],\
      '6':[sx,sy-0.3*rz+oz,sz-rz],\
      '7':[sx,sy-0.3*rz+oz,sz+rz],\
      '8':[sx,sy,sz],\
      '9':[sx,sy+0.3*rz+oz,sz-rz],\
      '10':[sx,sy+0.3*rz+oz,sz+rz],\
      '11':[sx,sy+rz+oz,sz],\
      '12':[sx+3,sy-rz,sz],\
      '13':[sx+3,sy,sz-rz],\
      '14':[sx+3,sy,sz+rz],\
      '15':[sx+3,sy+rz,sz]}
    slices={'0':['8','0','1','13','2','14'],\
      '1':['8','0','3','4','12','15'],\
      '2':['8','11','9','6','5','7','10']}
   
    print(slices['0'])

    fp={x:[pts[q] for q in slices[x]] for x in slices}
    
    sliceIds={x:[] for x in pts}
    for p in pts:
       for s in slices:
          if p in slices[s]:
             sliceIds[p].append(s)
    
    sliceCode={x:';'.join(sliceIds[x]) for x in sliceIds}
    print(fp)
    print(sliceCode)
    return fp

    #tip
    fp={'0':[\
            [sx,sy,sz],   
            [sx-5,sy,sz],\
            [sx-2,sy,sz-rz],\
            [sx+3,sy,sz-rz],\
            [sx-2,sy,sz+rz-1],\
            [sx+3,sy,sz+rz]],\
        '1':[\
            [sx,sy,sz],  
            [sx-5,sy,sz],\
            [sx-1,sy-rz,sz],\
            [sx-1,sy+rz-1,sz],\
            [sx+3,sy-rz,sz],\
            [sx+3,sy+rz,sz]],\
        '2':[\
            [sx,sy,sz],
            [sx,sy+rz+oz,sz],\
            [sx,sy+0.3*rz+oz,sz-rz],\
            [sx,sy-0.3*rz+oz,sz-rz],\
            [sx,sy-rz+oz,sz],\
            [sx,sy-0.3*rz+oz,sz+rz],\
            [sx,sy+0.3*rz+oz,sz+rz]]}
    return fp

def guessPixelPosition4(sx=-1,sy=-1,sz=-1):
    #guess position of segments
    if sx<0:
        sx=32
    if sy<0:
        sy=31
    if sz<0:
        sz=31
    rz=4

    pts={
      '0':[sx,sy,sz],\
      '1':[sx,sy,sz-rz],\
      '2':[sx,sy,sz+rz],\
      '3':[sx,sy-rz,sz],\
      '4':[sx,sy+rz,sz]}
    slices={
      '0':['0','1','2'],\
      '1':['0','3','4'],\
      '2':['0','1','2','3','4']}
   
    print(slices['0'])

    fp={x:[pts[q] for q in slices[x]] for x in slices}
    
    sliceIds={x:[] for x in pts}
    for p in pts:
       for s in slices:
          if p in slices[s]:
             sliceIds[p].append(s)
    
    sliceCode={x:';'.join(sliceIds[x]) for x in sliceIds}
    print(fp)
    print(sliceCode)
    return [{'regionId':x,'x':pts[x][0],'y':pts[x][1],'z':pts[x][2],'sliceId':sliceCode[x]} for x in pts]

def updateSegmentation(db,setup,r,pixels):
   copyFields=['PatientId','visitName']
   for x in pixels:
      for c in copyFields:
         x[c]=r[c]
      x['SequenceNum']=r['SequenceNum']+0.01*int(x['regionId'])
      filterVar=['PatientId','SequenceNum']
      qFilter=[{'variable':y,'value':'{}'.format(x[y]),'oper':'eq'} for y in filterVar]
      ds=db.selectRows(setup['project'],'study','Segmentation',qFilter)
      entry={}
      mode='insert'
      if len(ds['rows'])>0:
         entry=ds['rows'][0]
         mode='update'
      for q in x:
         entry[q]=x[q]
      db.modifyRows(mode,setup['project'],'study','Segmentation',[entry])
   print('Done')
     

def getPatientNIM(r,setup):
    locDir=config.getLocalDir(r,setup)
    fileName=config.getNodeName(r,setup,'NM',19)+'.nrrd'
    f=os.path.join(locDir,fileName)
    im=SimpleITK.ReadImage(f)
    nim=SimpleITK.GetArrayFromImage(im)
    return nim

def writeSegmentation(db,r,setup):
    locDir=config.getLocalDir(r,setup)
    fileName='{}_Segmentation.txt'.format(config.getCode(r,setup))
    idFilter={'variable':'PatientId','value':config.getPatientId(r,setup),'oper':'eq'}
    visitFilter={'variable':'visitName','value':config.getVisitId(r,setup),'oper':'eq'}
    rows=getData.getSegmentation(db,setup,[idFilter,visitFilter])
    v=numpy.zeros((len(rows),3))
    for qr in rows:
        region=int(qr['regionId'])
        v[region,2]=float(qr['x'])
        v[region,1]=float(qr['y'])
        v[region,0]=float(qr['z'])
    #for i in range(len(rows)):
    #    print(v[i,:])
    numpy.savetxt(os.path.join(locDir,fileName),v)
    
