# -*- coding: utf-8 -*-
from __future__ import print_function
import os
import utsusemi.ana.Reduction.BaseCommandsInEla as BaseCom
import Manyo.Utsusemi as mu
import Manyo as mm
#####################
# Command Sequence of Data Reduction
# 2018.07.18 ver 0.4 use BaseCommandsInEla
# 2015.04.22 ver 0.3 use GetNeunetHist
# 2010.11.10 ver 0.2 use GetHistogramOfEnergyTransfer
# 2010.05.18 ver 0.1
#####################

# special reserved word for commands history
HISTORY = None
# reserved words for return value in this.
DAT = None


########################################
def CopyData(first_run=10, last_run=-1):
    """
    Copy EventData file from DAQ0 or DAQ1 into /data/XXX
    @param runno_from (int) First Run No of a measurement to be copied
    @param runno_to (int) Last Run No of a measurement to be copied
    @retval None
    """
    BaseCom.CopyData(first_run, last_run)

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


def GetDataOfWhite(runNo=0, startTOF=0.0, endTOF=40000.0, binTOF=100, MaskFile="mask.txt", NormFactor=1000000.0, isCT8n=False):
    """
    Load EventData and convert to histogram using corrections as below:
    - GetNeunetHist( ... )
    - NormByBeamCurrent
    - DoMask
    - SolidAngleCorrection
    @param runNo      (int)    Run Number
    @param MaskFile   (string) file name for masking
    @param NormFactor (double) normalize factor data*factor/beamCurrent. if 0, do nothing.
    @retval DAT     (ElementContainerMatrix)
    """
    mu.UtsusemiMessage('DR.GetDataOfWhite({},{},{},{},"{}",{},{})'.format(
        runNo, startTOF, endTOF, binTOF, MaskFile, NormFactor, isCT8n), True)
    return BaseCom.GetDataOfWhite(runNo, startTOF, endTOF, binTOF, MaskFile, NormFactor, isCT8n)

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


def GetDataOfMonochroEi(runNo=0, Ei=0.0, Resolution=0.3, deltaE=0.0, L1=30.0, MaskFile="mask.txt", NormFactor=1000.0):
    """
    This Function is obsolete. Please forget me ...

    @param runNo    (int) Run Number
    @param Ei       (double) Incident Energy
    @param Resolution (double) Energy Resolution for tof binnings at Elastic Peak [%]
    @param deltaE   (double) Delta Energy Transfer [meV]
    @param L1       (double)  Distance between moderator to sample [m]
    @param MaskFile (string) file name for masking
    @param NormFactor (double) normalize factor data*factor/beamCurrent. if 0, do nothing.
    @retval DAT     ElementContainerMatrix as result
    """
    raise UserWarning("This Function is obsolete. Please forget me...")
    return None

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


def GetDataOfMonochroEi2(runNo=0, Ei=0.0, deltaE=0.0, Emin=0.0, Emax=0.0, MaskFile="Default", NormFactor=1000000.0, offset_sec=0.0, isCT8n=True, DetEffi="None"):
    """
    Load EventData and convert to histogram using corrections as below:
    - GetNeunetHist( ... ) including MaskInfo
    - NormByBeamCurrent(DAT,NormFactor)
    - SolidAngleCorrection(DAT)
    - kikfCorrection(DAT)
    - dHWCorrection(DAT)
    - DetectorEffi(DAT, DetEffi) # if DetEffi!="None"
    @param runNo    (int) Run Number
    @param Ei       (double) Incident Energy [meV]
    @param deltaE   (double) Delta Energy Transfer [meV]
    @param Emin     (double) minimum of Energy Transfer [meV]
    @param Emax     (double) maximum of Energy Transfer [meV]
    @param MaskFile (string) file name for masking
    @param NormFactor (double) normalize factor: Intensity/beamCurrent*factor. If 0, do nothing. If minus, Intensity/abs(factor)
    @param offset_sec (float) offset second for Measurement Period to get protons
    @param isCT8n (bool) use CT8Neutron ( corrected by muon target effect ) or not
    @param DetEffi (string) File name of the detector efficiency correction data. "None" : do not correction
    @retval DAT     ElementContainerMatrix as result
    """
    mu.UtsusemiMessage('DR.GetDataOfMonochroEi2({},{},{},{},{},"{}",{},{},{},"{}")'.format(
        runNo, Ei, deltaE, Emin, Emax, MaskFile, NormFactor, offset_sec, isCT8n, DetEffi), True)
    return BaseCom.GetDataOfMonochroEi2(runNo, Ei, deltaE, Emin, Emax, MaskFile, NormFactor, offset_sec, isCT8n, DetEffi)

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


def GetDataOfMonochroEi3(runNo="0", Ei=0.0, deltaE=0.0, Erange="0.0 0.0", TimeSlice="-1.0 -1.0", MaskFile="Default", NormFactor=1000000.0, offset_sec=0.0, isCT8n=True, PulseHeight="-", TimeDepBack="DARK:None", DetEffi="None"):
    """
    Load EventData and convert to histogram using corrections as below:
    - GetNeunetHist( ... ) including MaskInfo
    - NormByBeamCurrent(DAT,NormFactor)
    - SolidAngleCorrection(DAT)
    - kikfCorrection(DAT)
    - dHWCorrection(DAT)
    - DetectorEffi(DAT, DetEffi) # if DetEffi!="None"
    @param runNo    (string) Run Number(s) "<run1>[,<run2>,...]"(delimitor is comma)
    @param Ei       (double) Incident Energy [meV]
    @param deltaE   (double) Delta Energy Transfer [meV]
    @param Erange   (string) min and max of Energy Transfer [meV] "<min>,<max>"(delimitor is comma or space)
    @param TimeSlice(string) start time and end time [seconds] "<min>,<max>"(delimitor is comma or space)
    @param MaskFile (string) file name for masking
    @param NormFactor (double) normalize factor: Intensity/beamCurrent*factor. If 0, do nothing. If minus, Intensity/abs(factor)
    @param offset_sec (float) offset second for Measurement Period to get protons
    @param isCT8n (bool) use CT8Neutron ( corrected by muon target effect ) or not
    @param PulseHeigh (string) PulseHeight range "min" or "min:max", if not use "-"
    @param TimeDepBack (string) Subtruct time-independent-background "TOF:34000-36000" or "DARK:20717"
    @param DetEffi (string) File name of the detector efficiency correction data. "None" : do not correction
    @retval DAT     ElementCotainerMatix as result
    """
    mu.UtsusemiMessage('DR.GetDataOfMonochroEi3("{}",{},{},"{}","{}","{}",{},{},{},"{}","{}","{}")'.format(
        runNo, Ei, deltaE, Erange, TimeSlice, MaskFile, NormFactor, offset_sec, isCT8n, PulseHeight, TimeDepBack, DetEffi), True)
    return BaseCom.GetDataOfMonochroEi3(runNo, Ei, deltaE, Erange, TimeSlice, MaskFile, NormFactor, offset_sec, isCT8n, PulseHeight, TimeDepBack, DetEffi)

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


def ToPowder(dat=DAT, startQ=-1.0, endQ=-1.0, deltaQ=0.1):
    """
    Convert data from crystal to powder

    @param dat [Def:DAT] (ElementContaienrMatrix)
    @param startQ (double) Q value of range; if minus, auto calculated
    @param endQ   (double) Q value of range; if minus, auto calculated
    @param deltaQ (double) binning of Q
    @retval ECM   (ElementContainerMatrix)
    """
    mu.UtsusemiMessage("DR.ToPowder({},{},{},{})".format(
        "<ElementContainerMatrix>", startQ, endQ, deltaQ), True)
    return BaseCom.ToPowder(dat, startQ, endQ, deltaQ)

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


def MakeRunList(start_run=-1, end_run=-1, output="./run_list.txt", flag_proton=4, offset_sec=0.0, isCT8n=False, devTemp="LS340", devGonio="Gonio-1"):
    """
    Make run list
    @param start_run (int) start run number to be listed.
    @param end_run (int) start run number to be listed.
    @param output (string) output file name
    @param flag_proton (int) 0: no protons, 1:protons only, 2:kickers only, 3:both, 4:all
    @param offset_sec (float) offset second for Measurement Period to get protons
    @param isCT8n (bool) use CT8Neutron ( corrected by muon target effect ) or not
    @param devTemp (string) The instance name of temperature Control device like "LS340", "7Tmagnet", ...
    @param devGonio (string) The instance name of Gonio Control device like "Gonio", "7Tmagnet-EA"(encoder's angle), "7Tmagnet-SA"(set angle), ...
    @return None
    """
    mu.UtsusemiMessage('DR.MakeRunList({},{},"{}",{},{},{},"{}","{}")'.format(
        start_run, end_run, output, flag_proton, offset_sec, isCT8n, devTemp, devGonio), True)
    BaseCom.MakeRunList(start_run, end_run, output, flag_proton,
                        offset_sec, isCT8n, devTemp, devGonio)

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


def CopyIroha2Params(first_run=10, last_run=-1, flag=0):
    """
    Copy Iroha2 Params and Log file from Iroha2 server into /data/Iroha2
    @param runno_from (int) First Run No of a measurement to be copied
    @param runno_to (int) Last Run No of a measurement to be copied
    @param flag  (int)  Flag for Copy(0) or Symbolic link(1) / default is Symbolic link or -1 for testing
    @retval None
    """
    mu.UtsusemiMessage("DR.CopyIroha2Params({},{},{})".format(
        first_run, last_run, flag), True)
    BaseCom.CopyIroha2Params(first_run, last_run, flag)


# Dictionary for entry the name of functions
_functions = {
    "CopyData": CopyData,
    "GetDataOfWhite": GetDataOfWhite,
    "GetDataOfMonochroEi": GetDataOfMonochroEi,
    "GetDataOfMonochroEi2": GetDataOfMonochroEi2,
    "GetDataOfMonochroEi3": GetDataOfMonochroEi3,
    "ToPowder": ToPowder,
    "MakeRunList": MakeRunList
}

_functionsOrder = [
    "CopyData",
    "GetDataOfWhite",
    "GetDataOfMonochroEi",
    "GetDataOfMonochroEi2",
    "GetDataOfMonochroEi3",
    "ToPowder",
    "MakeRunList"
]
