# -*- coding: utf-8 -*-

#####################
## Command Sequence of Elastic Scan
#####################

# special reserved word for commands history
from __future__ import print_function
HISTORY = None
# reserved words for return value in this.
DAT = None
ECA = None
EC = None

import Manyo as mm
import Manyo.Utsusemi as mu
import utsusemi.ana.Reduction.BaseCommandsInEla as BaseCom
import utsusemi.DNA.ana.Reduction.BaseCommandsDNA as BaseComDNA
import utsusemi.DNA.ana.Reduction.PeakFitBase as PF
import os
import re
import glob
import math
import datetime
import uGao.MPlot as mp
import utsusemi.DNA.ana.Reduction.ElasticScanBase as ES
import multiprocessing

def GetQETimeECMMulth(runNo=314,HwParam=" ",LambParam=" ",QParam=" ",TimeParam=" ",initFile="GetQEDataOfDNA.ini",search_dir="/home/dnaadmin/ana/setup/"):
    jobNum = int(multiprocessing.cpu_count())
    #jobNum = int(2)
    """
    if multiprocessing.cpu_count() > 8:
        jobNum = int(multiprocessing.cpu_count()-2)
    elif multiprocessing.cpu_count() >= 2:
        jobNum = int(multiprocessing.cpu_count()-1)
    else:
        jobNum = 1
    """
    if jobNum == 0:
        print("CPU count Error")
        return 0
    
    Timerange = TimeParam.split(",")
    starttime = float(Timerange[0])
    endtime = float(Timerange[1])
    TimeBin = float(Timerange[2])
    
    TotalBinNum = int(math.ceil((endtime-starttime)/TimeBin))
    Amari = TotalBinNum%jobNum
    print(Amari)
    
    
    Timelist = []
    stlist = []
    sttemp = starttime
    ettemp = 0.0
    for ii in range(jobNum):
        if ii != (jobNum-1):
            if Amari !=0:
                ettemp = sttemp+(TotalBinNum/jobNum+1)*TimeBin
                Amari -= 1
            else:
                ettemp = sttemp+(TotalBinNum/jobNum)*TimeBin
        else:
            ettemp = endtime

        print("start:%.2f\tend:%.2f\tinterval:%.2f\tCycle:%d" %(sttemp,ettemp,TimeBin,(ettemp-sttemp)/TimeBin))
        Timelist.append(str(sttemp)+","+str(ettemp)+","+str(TimeBin))
        stlist.append(str(sttemp))
        sttemp = ettemp
    
    #return 0
    joblist =[]
    for ii in range(jobNum):
        eachtimeparam = Timelist[ii]
        print(eachtimeparam)
        job = multiprocessing.Process(target = ES.GetQETimeECMMulthMain,args=(runNo,HwParam,LambParam,QParam,eachtimeparam,initFile,search_dir,True))
        joblist.append(job)
        job.start()
    
    for jj in joblist:
        jj.join()
        print("job", jj.name, "is finished")
   
    del joblist

    flag= 0
    for footer in stlist:
        #filePath = "/home/dnaadmin/DNA/tmp/"
        filename = "ECM_%d_%s_ES.bst" %(runNo, footer)
        #filePath = os.path.join( os.environ["UTSUSEMI_USR_PRIV_HOME"],"DNA","tmp",filename )
        filePath = os.path.join( mu.UtsusemiEnvGetUserDir(),"DNA","tmp",filename )
        #if os.path.exists(filePath+filename):
        if os.path.exists(filePath):
            print("%s exists" %(filePath))
            if flag == 0:
                ecm = BaseComDNA.ReadECM(filename)
                flag =1
            else:
                ecmtemp = BaseComDNA.ReadECM(filename)
                for ii in range(ecmtemp.PutTableSize()):
                    ecm.Add(ecmtemp.Put(ii))
        else:
            print("%s%s does not exists" %(filePath, filename))
    
    print(ecm.PutTableSize())
    BaseComDNA.OutputECM(ecm,"_ES")
#    return joblist,jobname
    print("ECMMulth is finished")
    
    return ecm




