#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
2021.08.05 Yamada
"""
import re
from xml.etree.ElementTree import*
from xml.dom import minidom
import os

import Manyo
import Manyo.DNA as md
import Manyo.Utsusemi as mu
import utsusemi.DNA.ana.Reduction.ElasticScanBase as ESB 
import utsusemi.DNA.ana.Reduction.BaseCommandsDNA as BCD
import Cmm
import ElasticScan

def xmlmodify(elem):
	rough_string = tostring(elem, 'utf-8')
	reparsed = minidom.parseString(rough_string)
	pretty = re.sub(r"[\t ]+\n", "", reparsed.toprettyxml(indent="\t"))
	pretty = pretty.replace(">\n\n\t<",">\n\t<")
	return pretty

def MakeCaseInfoXML(starttime,endtime,interval):
	ESXMLdata = Element("caseInfo")
	ESXMLcaseAmbiguity = SubElement(ESXMLdata,"caseAmbiguity")
	ESXMLcaseAmbiguity.text="1"
	ESXMLinitialCase = SubElement(ESXMLdata,"initialCase")
	ESXMLinitialCase.text="0"
	ESXMLfilters = SubElement(ESXMLdata, "filters")
	ESXMLcounters = SubElement(ESXMLdata, "founters")
	ESXMLtimeSlicing = SubElement(ESXMLdata, "timeSlicing")
	ESXMLtimeSlicing.set("type","1")

	t1 = starttime
	t2 = t1+interval
	ii = 1
	while(1):
		ESXMLtime = SubElement(ESXMLtimeSlicing,"time")
		ESXMLtime.text="%d,%d" %(t1, t2)
		ESXMLtime.set("caseId", str(ii))
		if t2 >= endtime :
			break
		else:
			t1 = t2
			t2 = t1+interval
			ii += 1

	output = xmlmodify(ESXMLdata)
    #fname = "xml/ESCaseInfo.xml"
	fname = os.path.join(os.getcwd(), "ESCaseInfo.xml")
	f = open (fname,"w")
	f.write(output)
	f.close()
	return fname
	
#ECM = ElasticScan.GetQETimeECMMulth(self.RunNo, HWParam, LambdaParam, QParam, TimeParam, inifile)
#def ESTimeSlice(RunNo=13167, dataFolder="/data",HWParam="", LambdaParam="", QParam="", inifile=""):
def ESTimeSlice(RunNo=13167, dataFolder="/data",HWParam="", LambdaParam="", QParam="", inifile="", cfile=""):
	#wfile = "xml/WiringInfo20170606TY.xml"
	UAR = mu.UtsusemiAnaEnvironReader("environ_ana.xml")
	_envparams = UAR.PutParamFiles(RunNo,0,True)
        #dfile = "xml/DetectorInfo20170606TY.xml"
	dfile = _envparams[1]
    #cfile = "xml/ESCaseInfo.xml"

#search_dir="/home/dnaadmin/ana/setup"
#filepath =os.path.join(search_dir,initFile)
	#filepath = "ESGUIParams.ini"
	filepath = inifile
	useT0ModCorr      = ESB.SearchInitParamBool("useT0ModCorr",filepath)
	useMonEff         = ESB.SearchInitParamBool("useMonEff",filepath)
	useILambdaCorr    = ESB.SearchInitParamBool("useILambdaCorr",filepath)
	useMonNormalCorr  = ESB.SearchInitParamBool("useMonNormalCorr",filepath)
	useProtonNormCorr = ESB.SearchInitParamBool("useProtonNormCorr",filepath)
	useSolidAngleCorr = ESB.SearchInitParamBool("useSolidAngleCorr",filepath)
	useDetEff         = ESB.SearchInitParamBool("useDetEff",filepath)
	useAbsoCorr       = ESB.SearchInitParamBool("useAbsoCorr",filepath)
	useEffCorr        = ESB.SearchInitParamBool("useEffCorr",filepath)
	useFileOutput     = ESB.SearchInitParamBool("useFileOutput",filepath)
	maskfilename          = ESB.SearchInitParamString("MASKfilename",filepath)
	laticetype        = ESB.SearchInitParamString("laticetype",filepath)
	sampletype        = ESB.SearchInitParamString("sampletype",filepath)
	sampleDataFile    = ESB.SearchInitParamString("sampleDataFile",filepath)
	factor            = float(ESB.SearchInitParamString("factor",filepath))
	t0_offset         = float(ESB.SearchInitParamString("t0_offset",filepath))
	background        = float(ESB.SearchInitParamString("background",filepath))
	#T. Yamada Add [121129]
	UseFastChopper    = ESB.SearchInitParamBool("UseFastChopper",filepath)
	#T. Yamada End [121129]


	#モニターのReduction（規格化用）
	#EC = Cmm.GetHistogramMon(self.runNo, True, self.LambdaParam, self.T0Shift, 0.0, False, self.TimeParam, FastChopperUse)  

	# WiringInfoファイルの作成
	#wfile = "/home/dnaadmin/ana/xml/ESGUIWiringInfo.xml"
	wfile = os.path.join(mu.UtsusemiEnvGetUserDir(), "ana", "xml", "ESGUIWiringInfo.xml")
	BCD.GetHistogramHW(runNo=RunNo,HwParam=HWParam,LambdaParam=LambdaParam,t0_offset=t0_offset,useT0ModCorr=False,TimeParam="-1.0/-1.0",UseFastChopper=UseFastChopper,tofOffsetFile="dummy",isHistogram=False,WIoutput= wfile)
	
	# DNA用ヒストグラム関数準備
	ECD = md.UtsusemiEventDataConverterDNA()

	# パラメータ読み込み
	ECD.LoadParamFiles(wfile,dfile,cfile)

	# イベント選別用Caseテーブル作成
	# （そのためTrigNETかNeunetのイベントを裏で読み込む）
	#ECD.MakeCaseTable(RunNo, dataFolder, "" )
	# MakeCaseTableコマンドがない（古い）バージョンの場合
	ECD.LoadTrignetEventFile(RunNo, dataFolder, "" )

	# ヒストグラム変換用領域をを確保
	ECD.SetHistAllocation()

	# イベントデータの読み込み
	ECD.LoadEventDataFiles(RunNo,dataFolder,"")


	# 読み込んだデータからそれぞれのEMCを取り出して、QEMapにする。
	ecm2 = Manyo.ElementContainerMatrix() #出力結果の格納先
	
	CaseInfoTree = parse(cfile).getroot()
	findtag = "timeSlicing/time"
	slicenum  = len(CaseInfoTree.findall(findtag))

	startQ = float(QParam.split(",")[0])
	endQ = float(QParam.split(",")[1])
	deltaQ = float(QParam.split(",")[2])
	
	for ii in range(1,slicenum+1):
		caseId = ii
		ecm1 = Manyo.ElementContainerMatrix()
		ECD.SetElementContainerMatrix( ecm1, caseId )
		#Mask
		Cmm.DoMask(ecm1, maskfilename)
		#Proton Currentでの規格化
		if useProtonNormCorr:
			Cmm.NormByBeamCurrent(ecm1,factor,offset_sec=0.0,isCT8n=True)

		if useILambdaCorr:
			ecm1 = Cmm.ILambdaCorrDNA(ecm1, EC, useMonEff)

		if useSolidAngleCorr:
			ecm1 = Cmm.SolidAngleCorrDNA(ecm1, useDetEff, useAbsoCorr,useEffCorr,sampletype,sampleDataFile)
		eca = Cmm.CreateQEMap(ecm1,startQ,endQ,deltaQ)
		
		findtag = "timeSlicing/time[@caseId='%d']" %(caseId)
		timerange = CaseInfoTree.find(findtag).text.split(",")
		
		hh=eca.PutHeader()
		hh.Add("StartTime",float(timerange[0]))
		hh.Add("EndTime",float(timerange[1]))
		eca.InputHeader(hh)
		ecm2.Add(eca)

		if ii==1:
			ecm2.InputHeader(hh)

		#eca.PutHeader().Dump()
		del ecm1
		del eca
	
	del ECD
        #EC = ElasticScan.ElasticScanTotalIntensity(ecm2, "-0.004,0.004", QParam, inifile)
	#ElasticScan.OutPutElasticScanECM(ecm2)
	return ecm2

def ConvertXaxisFromTimeToTemp(ecES,ecTLog):
	#ecES: Elastic intensity with time
	#ecTLog: Temperature Log
	ESXaxisTime = ecES.PutXList()
	TLogXaxis = ecTLog.PutXList()
	TLogYaxis = ecTLog.PutYList()

	xlist=[]
	ii = 0
	for ii in range(len(TLogXaxis)-1):
		xlist.append((TLogXaxis[ii]+TLogXaxis[ii+1])*0.5)

	from numpy import interp
	ESXaxisTemp = interp(ESXaxisTime,xlist,TLogYaxis)
	ec = Manyo.ElementContainer()
	ec.Add("Xaxis",ESXaxisTemp.tolist(), " Temperature[K] ")
	ec.Add("Yaxis",ecES.PutY(), ecES.PutUnit(ecES.PutYKey()))
	ec.Add("Eaxis",ecES.PutE())
	ec.InputHeader(ecES.PutHeader())
	ec.SetKeys("Xaxis","Yaxis","Eaxis")


	return ec


if __name__ == '__main__':
	MakeCaseInfoXML(0,180,60)
	ESTimeSlice(13167,"/data")
	
