#!/usr/bin/python
# -*- coding: utf-8 -*-

from __future__ import print_function
#import time,sys,os,math,glob,datetime,re,urllib,httplib,socket
import time,sys,os,math,glob,datetime,re,urllib,socket
import Manyo as mm
import Manyo.Utsusemi as mu
import Manyo.DNA as md

import utsusemi.ana.Reduction.BaseCommandsInEla as BaseCom
import utsusemi.DNA.ana.Reduction.PeakFit as PF
import shutil
ver = float(sys.version_info[0])+float(sys.version_info[1])*0.1
if ver<2.5:
    from elementtree.ElementTree import ElementTree
else:
    from xml.etree.ElementTree import ElementTree

from utsusemi.DNA.ana.Reduction.DefaultInstParams import *
socket.setdefaulttimeout(1)
#------------------------------------------------------------------------------------------------------------

#------------------------------------------------------------------------------------------------------------
def CheckSampleTempByRunNumber(runNo,temptype): 
        """ 
         Check Sample Temperature by using LakeShore-350 recorded by IROHA2 Device method. 
         @param runNo      (int) 
         @param temptype   (string) 
         @retval EC        (ElementContainer) 
 
        """ 
        TimeParam="-1.0,-1.0" 
        
        #from DNA.ana.Reduction.BaseCommandsDNA import CheckRealTime
        #startday,starttime,endday,endtime = CheckRealTime(runNo,TimeParam) 
        
        #import DNA.ana.Reduction.TempMonitor as TM 
        resultEC = CheckSampleTemp(runNo,temptype,True) 
        resultEC.AddToHeader("RUNNUMBER",str(runNo)) 
        return resultEC
#------------------------------------------------------------------------------------------------------------
def CheckSampleTemp(runNo=9949,tempType="D2",ECOutPut=True): 
     """
         Check Sample Temperature by using LakeShore-350 and IROHA2
         @param runNo      (string) runNo
         @param thermoType   (string) select temperature channel (A, B, C, D, D2, D3, D4, D5)
         @param ECOutPut   (bool) output EC (True) or Meanvalue (False)
         @retval result    (array)
     """

     funcName = "CheckSampleTemp"
     #Check temperature sensor
     thermoType = GetthermoType(tempType) 
     
     #Check file
     #basepath = os.path.join(os.environ["UTSUSEMI_DATA_DIR"], os.environ["UTSUSEMI_SYS_NAME"])
     basepath = mu.UtsusemiEnvGetInstDataDir()

     #searchpath = "%s%06d_????????" %(os.environ["UTSUSEMI_SYS_NAME"], int(runNo))
     searchpath = "%s%06d_????????" %(mu.UtsusemiEnvGetInstCode(), int(runNo))
     result = glob.glob(os.path.join(basepath,searchpath))
     print(basepath)
     print(searchpath)
     print(result)
     
     if ("TC" in tempType):
          filepath = "Logs/LS350HTStickWithTC_Loop1%06d.log" %(int(runNo))
     elif ("PEACE_U" in tempType):
          filepath = "Logs/LS350PEACE_U_Loop1%06d.log" %(int(runNo))
          if ("UB" in tempType):
              filepath = "Logs/LS350IVCBottomLoop1%06d.log" %(int(runNo))
     elif ("PEACE_M" in tempType):
          filepath = "Logs/LS350PEACE_M_Loop3%06d.log" %(int(runNo))
          if ("MB" in tempType):
              filepath = "Logs/LS350IVCBottomLoop1%06d.log" %(int(runNo))
     elif ("PEACE_L" in tempType):
          filepath = "Logs/LS350PEACE_L_Loop4%06d.log" %(int(runNo))
          if ("LB" in tempType):
              filepath = "Logs/LS350IVCBottomLoop1%06d.log" %(int(runNo))
     else:
          filepath = "Logs/LS350Loop1%06d.log" %(int(runNo))
     print(filepath)
     if len(result) > 0:
          if os.path.exists(os.path.join(result[0],filepath)):
              filepath = os.path.join(result[0],filepath)
          else:
              print("%s >>> is %s does not exists." %(funcName, filepath))
    
     print("%s >>> filepath is %s." %(funcName, filepath))

     ####################################################################################################

     #Open file
     f = open(filepath)
     lines = f.readlines()
     f.close()
     line_num = len(lines)

     start_num=0
     end_num=0

     dt = datetime.datetime
     start_time_obj = dt.strptime(lines[0].split(",")[0],"%Y-%m-%d %H:%M:%S")

     time_array = []
     temperatures = []
     elist = []

     for line in lines:
          infos = line.split(",")
          #if len(infos) >= 12:
          if len(infos) >= 2:
               time_array.append((dt.strptime(infos[0],"%Y-%m-%d %H:%M:%S")-start_time_obj).seconds)
               temperatures.append(float(infos[thermoType]))
               elist.append(0.0)

     x1list = time_array[1:]
     x2list = time_array[:-1]
     xlist = [(x1+x2)*0.5 for x1, x2 in zip(x1list,x2list)]
     
     del x1list, x2list
     xlist.insert(0,time_array[0]-(xlist[0]))
     xlist.append(time_array[-1]+(time_array[-1]-time_array[-2])*0.5)
    
     print(xlist[0],xlist[-1],xlist[-2])

     result_ec = mm.ElementContainer()
     result_ec.Add("Xaxis",xlist,"sec")
     result_ec.Add("Yaxis",temperatures,"K")
     result_ec.Add("Eaxis",elist)
     result_ec.SetKeys("Xaxis","Yaxis","Eaxis")

#     f = open("test.csv","w")
#     for ii in range(len(xlist)):
#          f.write("%s, %s\n" %(xlist[ii],temperatures[ii]))
#     f.close()


     return result_ec
#     end_num = len(time_array)
#
#     print "start_time_h", start_time_h
#     print "end_time_h", end_time_h 
#     start_day = 2+365*12
#
#     # calclation of mean min max and so on
#
#     start_val = checkStartEndVal(list_array,start_num,param,thermoType)
#     end_val = checkStartEndVal(list_array,(end_num-1),param,thermoType)
#     min_val,max_val,sum_val,time_integral = CalcVal(list_array,start_num,end_num,param,thermoType,time_array)
#
#     # append calc result      
#
#     result = []
#     if abs(time_integral) < 0.00001:
#           print "integral of data is zero ?? please check start-time and end time"
#           print time_integral 
#           for i in range(0,20):
#                 result.append(0)
#     else:
#           result.append(float(sum_val/time_integral))
#           result.append(float(min_val))
#           result.append(float(max_val))
#           result.append(float(start_val))
#           result.append(float(end_val))
#
#     print "TemperatureRead >> Temp[K]: mean=%.2f,\tmin=%.2f,\tmax=%.2f,\tstart=%.2f,\tend=%.2f"\
#            %(result[0], result[1], result[2], result[3], result[4])
#  
#   #           result_ec = mm.ElementContainer()
#   #           result = []
#   #           return result,result_ec
#     # put value to ElementContainer
#     Xaxis = time_array
#     Yaxis = []
#     Eaxis = []
#
#     if ECOutPut :
#          if len(Xaxis)>2:
#               for i in range(len(Xaxis)-1):
#                    TM1 = checkStartEndVal(list_array,i,param,thermoType)
#                    TM2 = checkStartEndVal(list_array,i+1,param,thermoType)
#                    Yaxis.append((TM1+TM2)/2)
#                    Eaxis.append(0)
#
#               result_ec = mm.ElementContainer()
#               result_ec.Add("Xaxis",Xaxis,"sec")
#               result_ec.Add("Yaxis",Yaxis,"K")
#               result_ec.Add("Eaxis",Eaxis)
#               result_ec.SetKeys("Xaxis","Yaxis","Eaxis")
#
#              #p = mp.MPlot(result_ec)
#              #p.SetPlotParam(0,ls="-",lw=4,mk="",eb=False)
#              #p.SetYLabel("Temperature")
#              #p.SetXLabel("Time")
#              #subTitle = date1+" "+start_time+" ~ "+date2+" "+end_time
#              #p.SetSubTitle(subTitle)
#
#               return result_ec
#          else:
#               result_ec = mm.ElementContainer()
#               return result_ec
#     else:
#          return result
#     ##### -> TI & TY [20130121]
#######################################################################################

def checkStartEndVal(list_array,ii,param,thermoType):

     if(ii<len(list_array)):
          return_val = list_array[ii][param+(thermoType-1)*2]
     else:
          print("Check ii>", ii)
          reurn_val = 0

     if return_val=="": return_val1=0
     return float(return_val)

######################################################################################

def CalcVal(list_array,start_num,end_num,param,thermoType,time_array):

     sum_val = 0
     min_val = 10000
     max_val = 0
     time_integral = 0

     for i in range(start_num,end_num-1):
       if list_array[i][1] =="STATUS":

           if list_array[i][param+(thermoType-1)*2] == "":
               print("Check thermoType")              
               val = 0
           else:
               val =  float(list_array[i][param+(thermoType-1)*2])
               sum_val += val * (time_array[i+1] - time_array[i])
               time_integral += time_array[i-start_num+1] - time_array[i-start_num]
               if min_val>val:
                    min_val=val
               if max_val<val:
                    max_val=val

     return min_val,max_val,sum_val,time_integral

######################################################################################
def GetthermoType(TCh="D"):
    if(TCh=="A"):
        return 2
    elif(TCh=="B"):
        return 3
    elif(TCh=="C")or(TCh=="C_TC"):
        return 4
    elif(TCh=="D")or(TCh=="D1")or(TCh=="D_TC"):
        return 5
    elif(TCh=="D2")or(TCh=="PEACE_U"):
        return 6
    elif(TCh=="D3")or(TCh=="PEACE_M")or(TCh=="PEACE_UB"):
        return 7
    elif(TCh=="D4")or(TCh=="PEACE_L")or(TCh=="PEACE_MB"):
        return 8
    elif(TCh=="D5")or(TCh=="PEACE_LB"):
        return 9
    elif(int(TCh)>=1 and int(TCh)<=10):
        return int(TCh)
    else:
        return 4
######################################################################################


if __name__ == '__main__':
    ec = CheckSampleTemp(20740, "PEACE_U", True)
    import uGao.MPlot as mp
    mp.MPlot(ec)
