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

import os
import numpy as np
import scipy.optimize
import Manyo.SAS as ms
import Manyo as mm
import math
import utsusemi.SAS.ana.Reduction.HistBaseCommands as HBC
import utsusemi.SAS.ana.Reduction.CorrBaseCommands as CBC
"""
Base Functions for SAS
Trans.py
- GetTransNormByMonCounts
- GetTransNormByMonCountsTS
- GetTransNormByMon
- GetTransNormByMonTS
"""

#########################################
def GetTransNormByMonCounts(SmplRunNo="104000", DrctRunNo="104000", AxType="lambda", XRange="0.7 7.6 0.1", frameBoundary=0.0, CalibEffi=True, paramFiles="- -" ):
    """
    Monitor histogram of sample and direct followed by a transmittance calculation.
    @param SmplRunNo     (string)    Sample measurement run number
    @param DrctRunNo     (string)    Direct beam measurement run number
    @param AxType        (string)  Type must be "tof', "lambda" or "lamda2"
    @param XRange        (string) "startX endX widthX" separated with space (not comma)
    @param frameBoundary (float)
    @param CalibEffi     (bool)    Monitor-detector efficiency calibration
    @param paramFiles    (string) "<wiringInfo> <detectorInfo>[ <caseInfo>]"
    @retval list of Tr
    """
    import Com
    s = XRange.split()
    norm_range = "%s %s"%(s[0], s[1])

    smpl1s = HBC.GetMonHistSAS(SmplRunNo, 1, AxType, XRange, 0, "-1 -1", str(frameBoundary), CalibEffi, paramFiles=paramFiles)
    smpl2s = HBC.GetMonHistSAS(SmplRunNo, 2, AxType, XRange, 0, "-1 -1", str(frameBoundary), CalibEffi, paramFiles=paramFiles)
    if type(smpl1s)!=list:
        smpl1s = [smpl1s]
        smpl2s = [smpl2s]
    for smpl1, smpl2 in zip(smpl1s,smpl2s):
        CBC.NormByMonCounts(smpl2, smpl1, "Lamb", norm_range, 1.0)

    drct1 = HBC.GetMonHistSAS(DrctRunNo, 1, AxType, XRange, 0, "-1 -1", str(frameBoundary), CalibEffi)
    drct2 = HBC.GetMonHistSAS(DrctRunNo, 2, AxType, XRange, 0, "-1 -1", str(frameBoundary), CalibEffi)
    CBC.NormByMonCounts(drct2, drct1, "Lamb", norm_range, 1.0)

    ret = []
    for smpl2 in smpl2s:
        ret.append( Com.ExecFunctionCode("A/B", smpl2, drct2) )
    if len(ret)==1:
        return ret[0]
    return ret

#########################################
def GetTransNormByMonCountsTS(SmplRunNo="104000", DrctRunNo="104000", AxType="lambda", XRange="0.7 7.6 0.1", frameBoundary=0.0, CalibEffi=True, SmplTSlice="-1 -1", DrctTSlice="-1 -1", paramFiles="- -"):
    """
    Monitor histogram of sample and direct followed by a transmittance calculation.
    @param SmplRunNo     (string)    Sample measurement run number
    @param DrctRunNo     (string)    Direct beam measurement run number
    @param AxType        (string)  Type must be "tof', "lambda" or "lamda2"
    @param XRange        (string) "startX endX widthX" separated with space (not comma)
    @param frameBoundary (float)
    @param CalibEffi     (bool)    Monitor-detector efficiency calibration
    @param SmplTSlice    (string) Time Slice parameters for Sample run
    @param DrctTSlice    (string) Time Slice parameters for Directrun
    @param paramFiles    (string) "<wiringInfo> <detectorInfo>[ <caseInfo>]
    @retval Tr
    """
    import Com
    s = XRange.split()
    norm_range = "%s %s"%(s[0], s[1])

    smpl1s = HBC.GetMonHistSAS(SmplRunNo, 1, AxType, XRange, 0, SmplTSlice, str(frameBoundary), CalibEffi, paramFiles=paramFiles)
    smpl2s = HBC.GetMonHistSAS(SmplRunNo, 2, AxType, XRange, 0, SmplTSlice, str(frameBoundary), CalibEffi, paramFiles=paramFiles)
    if type(smpl1s)!=list:
        smpl1s = [smpl1s]
        smpl2s = [smpl2s]
    for smpl1,smpl2 in zip(smpl1s,smpl2s):
        CBC.NormByMonCounts(smpl2, smpl1, "Lamb", norm_range, 1.0)

    drct1 = HBC.GetMonHistSAS(DrctRunNo, 1, AxType, XRange, 0, DrctTSlice, str(frameBoundary), CalibEffi)
    drct2 = HBC.GetMonHistSAS(DrctRunNo, 2, AxType, XRange, 0, DrctTSlice, str(frameBoundary), CalibEffi)
    CBC.NormByMonCounts(drct2, drct1, "Lamb", norm_range, 1.0)

    ret = []
    for smpl2 in smpl2s:
        ret.append(Com.ExecFunctionCode("A/B", smpl2, drct2))
    if len(ret)==1:
        return ret[0]
    return ret

#########################################
def GetTransNormByMon(SmplRunNo="104000", DrctRunNo="104000", Xrange="0.7 7.6 0.1 dL", frameBoundary="0.0", CalibEffi=True, useMon="MON1", paramFiles="- -" ):
    """
    Monitor histogram of sample and direct followed by a transmittance calculation.
    @param SmplRunNo     (string)    Sample measurement run number
    @param DrctRunNo     (string)    Direct beam measurement run number
    @param Xrange        (string)  "startX endX widthX type" separated with space (not comma) : type=[dL, dL/L, tof]
    @param frameBoundary (float)
    @param CalibEffi     (bool)    Monitor-detector efficiency calibration
    @param useMon        (strng)  Upstream Monitor (MON1 or MON3)
    @param paramFiles    (string) "<wiringInfo> <detectorInfo>[ <caseInfo>]
    @retval Tr
    """
    import Com
    s = Xrange.split()
    norm_range = "%s %s"%(s[0], s[1])

    x_range = Xrange.split( " " )
    AxType=""
    if len(x_range)!=4:
        raise UserWarning("Xrange is invalid.")
    if x_range[3] == "dL":
        AxType = "lambda"
    elif x_range[3] == "dL/L":
        AxType = "lambda2"
    elif x_range[3] == "tof":
        AxType = "tof"
    else:
        raise UserWarning("Xrange is invalid.")
    XRange = "%s %s %s"%(x_range[0],x_range[1],x_range[2])

    monUpStream = 1
    if useMon=="MON1":
        monUpStream = 1
    elif useMon=="MON3":
        monUpStream = 3
    else:
        raise UserWarning("useMon is invalid.")

    smpl1s = HBC.GetMonHistSAS(SmplRunNo, monUpStream, AxType, XRange, 0, "-1 -1", frameBoundary, CalibEffi, paramFiles=paramFiles)
    smpl2s = HBC.GetMonHistSAS(SmplRunNo, 2, AxType, XRange, 0, "-1 -1", frameBoundary, CalibEffi, paramFiles=paramFiles)
    if type(smpl1s)!=list:
        smpl1s = [smpl1s]
        smpl2s = [smpl2s]
    for smpl1,smpl2 in zip(smpl1s,smpl2s):
        CBC.NormByMonCounts(smpl2, smpl1, "Lamb", norm_range, 1.0)

    drct1 = HBC.GetMonHistSAS(DrctRunNo, monUpStream, AxType, XRange, 0, "-1 -1", frameBoundary, CalibEffi)
    drct2 = HBC.GetMonHistSAS(DrctRunNo, 2, AxType, XRange, 0, "-1 -1", frameBoundary, CalibEffi)
    CBC.NormByMonCounts(drct2, drct1, "Lamb", norm_range, 1.0)

    ret = []
    for smpl2 in smpl2s:
        ret.append(Com.ExecFunctionCode("A/B", smpl2, drct2))
    if len(ret)==1:
        return ret[0]
    return ret

#########################################
def GetTransNormByMonTS(SmplRunNo="104000", DrctRunNo="104000", Xrange="0.7 7.6 0.1 dL", frameBoundary="0.0", CalibEffi=True, SmplTSlice="-1 -1", DrctTSlice="-1 -1", useMon="MON1", paramFiles="- -"):
    """
    Monitor histogram of sample and direct followed by a transmittance calculation.
    @param SmplRunNo     (string)    Sample measurement run number
    @param DrctRunNo     (string)    Direct beam measurement run number
    @param Xrange        (string)  "startX endX widthX type" separated with space (not comma) : type=[dL, dL/L, tof]
    @param frameBoundary (float)
    @param CalibEffi     (bool)    Monitor-detector efficiency calibration
    @param SmplTSlice    (string) Time Slice parameters for Sample run
    @param DrctTSlice    (string) Time Slice parameters for Directrun
    @param useMon        (strng)  Upstream Monitor (MON1 or MON3)
    @param paramFiles    (string) "<wiringInfo> <detectorInfo>[ <caseInfo>]
    @retval Tr
    """
    import Com
    s = Xrange.split()
    norm_range = "%s %s"%(s[0], s[1])

    x_range = Xrange.split( " " )
    AxType=""
    if len(x_range)!=4:
        raise UserWarning("Xrange is invalid.")
    if x_range[3] == "dL":
        AxType = "lambda"
    elif x_range[3] == "dL/L":
        AxType = "lambda2"
    elif x_range[3] == "tof":
        AxType = "tof"
    else:
        raise UserWarning("Xrange is invalid.")
    XRange = "%s %s %s"%(x_range[0],x_range[1],x_range[2])

    monUpStream = 1
    if useMon=="MON1":
        monUpStream = 1
    elif useMon=="MON3":
        monUpStream = 3
    else:
        raise UserWarning("useMon is invalid.")

    smpl1s = HBC.GetMonHistSAS(SmplRunNo, monUpStream, AxType, XRange, 0, SmplTSlice, frameBoundary, CalibEffi, paramFiles=paramFiles)
    smpl2s = HBC.GetMonHistSAS(SmplRunNo, 2, AxType, XRange, 0, SmplTSlice, frameBoundary, CalibEffi, paramFiles=paramFiles)
    if type(smpl1s)!=list:
        smpl1s = [smpl1s]
        smpl2s = [smpl2s]
    for smpl1,smpl2 in zip(smpl1s,smpl2s):
        CBC.NormByMonCounts(smpl2, smpl1, "Lamb", norm_range, 1.0)

    drct1 = HBC.GetMonHistSAS(DrctRunNo, monUpStream, AxType, XRange, 0, DrctTSlice, frameBoundary, CalibEffi)
    drct2 = HBC.GetMonHistSAS(DrctRunNo, 2, AxType, XRange, 0, DrctTSlice, frameBoundary, CalibEffi)
    CBC.NormByMonCounts(drct2, drct1, "Lamb", norm_range, 1.0)

    ret = []
    for smpl2 in smpl2s:
        ret.append(Com.ExecFunctionCode("A/B", smpl2, drct2))
    if len(ret)==1:
        return ret[0]
    return ret
