from __future__ import print_function
import os
import datetime


def AppendRawDataFiles(OutRunNo=990000, outDataPath="-", RunNo1=0, RunNo2=0, RunNo3=0, RunNo4=0, RunNo5=0, RunNo6=0):
    """
    append several EventData iles into one

    @param OutRunNo (int) output run number
    @param outDataPath (string) output data path (default is empty)
    @param RunNo1   (int) run number 1
    @param RunNo2   (int) run number 2
    @param RunNo3   (int) run number 3
    @param RunNo4   (int) run number 4
    @param RunNo5   (int) run number 5
    @param RunNo6   (int) run number 6
    @retval None
    """
    RunNoList = []
    if RunNo1 > 0:
        RunNoList.append(RunNo1)
    if RunNo2 > 0:
        RunNoList.append(RunNo2)
    if RunNo3 > 0:
        RunNoList.append(RunNo3)
    if RunNo4 > 0:
        RunNoList.append(RunNo4)
    if RunNo5 > 0:
        RunNoList.append(RunNo5)
    if RunNo6 > 0:
        RunNoList.append(RunNo6)

    if len(RunNoList) == 0:
        raise UserWarning("No run number was set.")

    mlf_DataPath = os.path.join(
        os.environ["UTSUSEMI_DATA_DIR"], os.environ["UTSUSEMI_INST_CODE"])

    if outDataPath == "-":
        outDataPath = mlf_DataPath
    if not os.path.exists(outDataPath):
        raise UserWarning("No Data path=%" % (outDataPath))

    existed_Dirs = os.listdir(mlf_DataPath)
    existed_Dirs.sort()
    target_Dirs = []
    inst_code = ""

    # find directory such a XXXnnnnnn_yyyymmdd
    for i in range(len(existed_Dirs)):
        a_dir = existed_Dirs[i]

        if len(a_dir) != 18 or a_dir[9] != "_":
            continue
        else:
            inst_code = a_dir[:3]

            if int(a_dir[3:9]) in RunNoList:
                target_Dirs.append(os.path.join(mlf_DataPath, a_dir))

            if int(a_dir[3:9]) == OutRunNo:
                raise UserWarning(
                    "OutRunNo(%06d) already exists." % (OutRunNo))

    if len(target_Dirs) == 0:
        raise UserWarning(
            " There is no data of given run numbers in %s" % (mlf_DataPath))

    # copy files in first directory
    efiles = os.listdir(target_Dirs[0])
    id_dic = {}
    from_Dirs = {}
    print(target_Dirs[0][-15:-9])

    for target_dir in target_Dirs:
        efiles = os.listdir(target_dir)
        # [-15:-9]=nnnnnn runNo
        from_Dirs[int(target_dir[-15:-9])] = target_dir

        for efile in efiles:
            # XXXnnnnnn_DD_MMM_NNN.edb
            if (efile[-3:] == "edb"):
                key = efile[10:16]        # DD_MMM
                run_no = int(efile[3:9])  # nnnnnn
                if key in id_dic:
                    if not (run_no in id_dic[key]):
                        id_dic[key].append(run_no)
                else:
                    id_dic[key] = [run_no]

    """
    for key in id_dic.keys():
        print "id_dic=",key,id_dic[key]

    for key in from_Dirs.keys():
        print "from_Dirs=",key,from_Dirs[key]



    id_dic2 = {}

    for key in id_dic.keys():
        if len( id_dic[key] )==len( RunNoList ):
            id_dic2[ key ] = id_dic[key]
    """

    id_dic2 = id_dic
    if outDataPath != mlf_DataPath:
        com = "mkdir -p %s" % (outDataPath)
        print(com)
        os.system(com)

    datenow = datetime.datetime.now()

    outDir = os.path.join(outDataPath, "%s%06d_%4d%02d%02d" % (
        inst_code, OutRunNo, datenow.year, datenow.month, datenow.day))
    com = "mkdir -p %s" % (outDir)
    print(com)
    os.system(com)

    for key in id_dic2:
        print("DAQ_Module=", key)
        id_dic2[key].sort()
        for i in range(len(id_dic2[key])):
            run_no = id_dic2[key][i]
            # print "run_no=",run_no
            ind = 0
            while(True):
                from_file = "%3s%06d_%s_%03d.edb" % (
                    inst_code, run_no, key, ind)
                to_file = "%3s%06d_%s_%03d.edb" % (inst_code, OutRunNo, key, 0)
                fullpath_from_file = os.path.join(from_Dirs[run_no], from_file)
                if os.path.exists(fullpath_from_file):
                    com = "cat %s >> %s" % (
                        fullpath_from_file, os.path.join(outDir, to_file))
                    print(com)
                    os.system(com)

                    ind += 1
                else:
                    break
