from __future__ import print_function
import os
import datetime
import Manyo as mm
import Manyo.Utsusemi as mu
import time as dtime
import uGao.MPlot as mp
filename = 'Log_TC_'

#def CheckSampleTemp(date1="2012-04-02",start_time="14:15:00",date2="2012-04-02",end_time="16:15:00",thermoType=1): T. Yamada comment out [121228]
def CheckSampleTemp(date1="2012-04-02",start_time="14:15:00",date2="2012-04-02",end_time="16:15:00",tempType="Si",ECOutPut=True): 
     """
         Check Sample Temperature by using LakeShore-340
         @param date1      (string) start date
         @param start_time (string) start time
         @param date2      (string) end date
         @param end_time   (string) end time
         @param thermoType   (string) select temperature channel (A, B, C, C2...)
         @param ECOutPut   (bool) output EC (True) or Meanvalue (False)
         @retval result    (array)
     """

     ####################################################################################################
     #
     #date1="2012-04-02"
     #date2="2012-04-02"

#    param = 43
     Time = date1 +" "+start_time
     st0 = datetime.datetime(*dtime.strptime(Time,"%Y-%m-%d %H:%M:%S")[0:6])
     dt1 = datetime.datetime(2012,0o5,1,0,0,0,)
     dt2 = datetime.datetime(2012,0o5,24,0,0,0,)
     dt3 = datetime.datetime(2012,0o6,0o5,0,0,0,)     #T. Yamada add[121129]

     if st0 < dt1:
        param = 43
     elif st0 > dt1 and st0 < dt2:
        param = 61
     elif st0 > dt2 and st0 < dt3:
        param = 61
    #T. Yamada add [121129]
     elif st0 > dt3:
        #param = 71
        param = 65 #T. Yamada Modified [121228]
    #T. Yamada end [121129]

     #T. Yamada add[121228]
     thermoType = GetthermoType(tempType) 
     #T.Yamada end[121228]
#     basepath = os.path.join(os.environ["HOME"],"advancesoft","miya_test")
     #basepath = os.path.join(os.environ["HOME"],"ana","tmp") #20141220[Yamada]
     basepath = os.path.join(mu.UtsusemiEnvGetUserDir(),"ana","tmp") #2023[Y.Inamura] 
     #basepath = os.path.join(os.environ["MLF_TOP_DIR"],"log","mw")


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

     # file open and connect

     start_time_list = start_time.split(":")
     end_time_list = end_time.split(":")

     filename1 = filename + date1 +".csv"
     filename2 = filename + date2 +".csv"

     filepath1 = os.path.join(basepath,filename1)
     filepath2 = os.path.join(basepath,filename2)

     print(filepath1)
     tmppath = os.path.join(basepath,"tmp")

     if date1 == date2:
          if os.path.exists(filepath1):
              os.system("cat " + filepath1 + " >" + tmppath)
          else:
              result_ec = mm.ElementContainer()
              result = []
              return result,result_ec
     else :
          if os.path.exists(filepath1) and os.path.exists(filepath2):          
              os.system("cat " + filepath1 + " " + filepath2+ " >" + tmppath)     
          else:
              result_ec = mm.ElementContainer()
              result = []
              return result,result_ec

     f = open(tmppath)
     lines = f.readlines()
     f.close()
     line_num = len(lines)

     list_array = []
     date_array = []
     time_array = []

     time_axis = []
    
     start_num=0
     end_num=0

     # search initial and final real time from log data
     ##### <- TI & TY [20130121]    
     start_time_h = datetime.datetime(*dtime.strptime((date1+" "+start_time),"%Y-%m-%d %H:%M:%S")[0:6])
     end_time_h = datetime.datetime(*dtime.strptime((date2+" "+end_time),"%Y-%m-%d %H:%M:%S")[0:6])
     start_time_h = start_time_h-datetime.timedelta(minutes=5)
     end_time_h = end_time_h+datetime.timedelta(minutes=10)

     temperatures = []

     for line in lines:
          infos = line.split(",")
          if infos[1] == "STATUS":
               tmain,tms = infos[0].split(".")
               date = datetime.datetime(*dtime.strptime(tmain,"%Y-%m-%d %H:%M:%S")[0:6])
               if date <= start_time_h:
                    pass
               elif date >= end_time_h:
                    break
               else:
                    date = date-start_time_h
                    #time_array.append(date.days*24*3600+date.seconds+float(tms)/1000) T.Yamada Modified [130226]
                    time_array.append(date.days*24*3600+date.seconds+float(tms)/1000-300)
                    list_array.append(infos)
     start_num = 0
     end_num = len(list_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]))
  
     # 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 DateArray2TimeArray(date_array,time_array,start_num,end_num,date1,date2):

     time_a =[]
     for i in range(start_num,end_num):
        if date_array[i][0] == date1:
            time_a.append((float(time_array[i][0])*60*60\
                          +float(time_array[i][1])*60\
                          +float(time_array[i][2]) )/(60*60*24))
        elif date_array[i][0] == date2:
            time_a.append(((float(time_array[i][0]) + 24.0)*60*60\
                           +float(time_array[i][1])*60\
                           +float(time_array[i][2]) )/(60*60*24))
        else:
            print("start-time and end-time infomation are not including in log-files")

     return time_a

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

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 CalcTime(list_array,start_num,end_num,param,thermoType,time_a,start_day):

     time_array = []
     time_array_m = []
     error_array = []
     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] != "":
               time_integral += time_a[i-start_num+1] - time_a[i-start_num]

           # Time define
           time = (time_a[i-start_num] + start_day)
#           time_m = (time_a[i-start_num]-time_a[0])*60*60*24

           time_array.append(time)
#           time_array_m.append(time_m)
#           error_array.append(0)

#     return time_integral,time_array,time_array_m,error_array
     return time_integral

######################################################################################
#T. Yamada start [121228]
def GetthermoType(TCh="C2"):
    if(TCh=="A"):
        return 1
    elif(TCh=="B"):
        return 2
    elif(TCh=="C")or(TCh=="C1"):
        return 3
    elif(TCh=="C2")or(TCh=="Si"):
        return 4
    elif(TCh=="C3"):
        return 5
    elif(TCh=="C4"):
        return 6
    elif(TCh=="D")or(TCh=="D1"):
        return 7
    elif(TCh=="D2")or(TCh=="Pt"):
        return 8
    elif(TCh=="D3"):
        return 9
    elif(TCh=="D4"):
        return 10
    elif(int(TCh)>=1 and int(TCh)<=10):
        return int(TCh)
    else:
        return 4
#T. Yamada end [121228]
######################################################################################
