#!/usr/bin/python3
# -*- coding: utf-8 -*-

from __future__ import print_function
import os
import sys
import time
import commands
"""
(2010.1.25) Bugfix for difference of directory name in /data/DAQ#/
"""


def _copydatasingle(runno=-1, flag=-1, target=""):
    """
    Copy or make symbolic link of Event Data from DAQ CPU to User CPU
    format Copydata(runno,[flag])
    @param runno(int) First 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 -1 No data in DAQ CPU
    @retval -2 False to make directory
    @retval -3 False to copy data file / make symbolic link
    @retval -4 Not agreement between origin data files and copied files
    @retval  0 success to execute
    """
    if flag == -1:
        print(" Copydata program runs on Dummy mode.")
    if runno == -1:
        print(" Copydata( first runno, last runno, flag=0:copy/1:Sybmolic link)")
        return
    RUNNO = "%06d" % runno
    # RUNNO = RUNNO.replace(" ", "0")
    HEAD = os.environ["UTSUSEMI_INST_CODE"] + RUNNO

    # ##Make List for pathes to EventData folder of given Run#
    if target == "":
        ROOTDIR_out = os.path.join(
            os.environ["UTSUSEMI_DATA_DIR"], os.environ["UTSUSEMI_INST_CODE"])
    else:
        ROOTDIR_out = target
    FOLDER_LIST = []  # for storing /data/DAQ#/XXX######_YYYYMMDD

    daq_id = 0
    FirstRunDir = ""
    while(True):
        DAQ_dir = "/data/DAQ%1d" % (daq_id)
        if not os.path.exists(DAQ_dir):
            break
        RunDir_list = os.listdir(DAQ_dir)
        RunDir = ""
        for A_dir in RunDir_list:
            if A_dir.find(HEAD) != -1:
                RunDir = A_dir
                if FirstRunDir == "":
                    FirstRunDir = A_dir
        if RunDir == "":
            print("Cannot find this Run Number :{} in {}".format(HEAD, DAQ_dir))
        else:
            FOLDER_LIST.append(os.path.join(DAQ_dir, RunDir))
        daq_id = daq_id + 1

    if len(FOLDER_LIST) == 0:
        print("No data of this Run Number:{} in all DAQ system.".format(HEAD))
        return -1

    '''
    ROOTDIRLIST=[]
    daq_id=0
    ROOTDIR="/data/DAQ%1d" % (daq_id)
    while(os.path.exists(ROOTDIR)):
        ROOTDIRLIST.append(ROOTDIR)
        daq_id=daq_id+1
        ROOTDIR="/data/DAQ%1d" % (daq_id)
    daq_no=daq_id-1

    ROOTDIR_out = os.environ["UTSUSEMI_DATA_DIR"]

    Folder_list = os.listdir(ROOTDIRLIST[0])
    Folder=""
    for A_Folder in Folder_list:
        if A_Folder.find(HEAD)!=-1:
            Folder=A_Folder
    if Folder=="":
        print "Cannot find such Run number =",HEAD
        return

    FOLDER_LIST=[]  ## for storing /data/DAQ#/XXX######_YYYYMMDD

    for FOLDER_d in ROOTDIRLIST:
        FOLDER_LIST.append( os.path.join(FOLDER_d,Folder) )

    FOLDER_to=os.path.join(ROOTDIR_out,Folder)  ## for storing /data/XXX/XXX######_YYYYMMDD
    '''
    # Make path and directory to output
    # for storing /data/XXX/XXX######_YYYYMMDD
    FOLDER_to = os.path.join(ROOTDIR_out, FirstRunDir)
    comm = "mkdir -p {}".format(FOLDER_to)
    print("Do command > {}".format(comm))
    if flag != -1:
        r1 = os.system(comm)
        if r1 != 0:
            print("False to make directory ({})".format(FOLDER_to))
            return -2

    # Make List of pathes for all event data to be copied
    EdataList = []
    for FOLDER_d in FOLDER_LIST:
        try:
            edata = os.listdir(FOLDER_d)

        except FileNotFoundError:
            print("Maybe there is no data folder. :{}".format(FOLDER_d))
        else:
            edata.sort()
            EdataList.append((FOLDER_d, edata))

    # Exucute coping files or making symbolic links of event data
    for (FOLDER, Edata) in EdataList:
        for onedata in Edata:
            if flag == 1:
                comm = "ln -s " + \
                    os.path.join(FOLDER, onedata) + " " + \
                    os.path.join(FOLDER_to, onedata)
            else:
                comm = "cp -fp " + \
                    os.path.join(FOLDER, onedata) + " " + \
                    os.path.join(FOLDER_to, onedata)
            print("Do command > {}".format(comm))
            if flag != -1:
                r1 = os.system(comm)
                if r1 != 0:
                    return -3

    # Check executed results
    if flag != -1:
        ES = []
        for F in FOLDER_LIST:
            try:
                E = os.listdir(F)
            except FileNotFoundError:
                print("Maybe there is no data folder :{}".format(F))
            else:
                ES = ES + E
        ES.sort()

        ET_tmp = os.listdir(FOLDER_to)
        ET = []
        for a_file in ET_tmp:
            if a_file[-4:] == ".edb" or a_file[-4:] == ".t0b":
                ET.append(a_file)
        ET.sort()

        for li in range(len(ES)):
            if ES[li] != ET[li]:
                print(
                    " WARNING!! : some files are not copied. {} -> {}".format(ES[li], ET[li]))

        if len(ES) != len(ET):
            if ET[-1] != FirstRunDir + "_info.txt":
                print(" ERROR!! : something was wrong!!.")
                return -4

    # Make information text about copied files
    Elist = []
    for FOLDER_d in FOLDER_LIST:
        ES = commands.getoutput("LANG='c';ls -l {}".format(FOLDER_d))
        EL = ES.split("\n")
        Elist = Elist + EL

    if flag != -1:
        fname = FirstRunDir + "_info.txt"
        ff = open(os.path.join(FOLDER_to, fname), "w")
        for line in Elist:
            ff.write(line + "\n")

        ff.close()

    else:
        print(Elist)

    return 0


def CopyEventData(firstrun=-1, lastrun=-1, flag=-1, target=""):
    """
    Copy Event data file

    @param firstrun (int) first run number
    @param lastrun  (int) last run number
    @param flag (int) 0:copy / 1:Symbolic link
    @retval list for return values of _copydatasingle
    """
    ret = []
    start_time = time.time()
    if (firstrun == -1) and (lastrun == -1):
        print(" Copydata( first runno, last runno, flag=0:copy/1:Sybmolic link)")
        return ret

    for runno in range(firstrun, (lastrun + 1)):
        rup_time = time.time()
        ret.append(_copydatasingle(runno, flag, target))
        print("time cost={}".format(time.time() - rup_time))
    print("Total time cost = {}".format(time.time() - start_time))

    return ret


if __name__ == '__main__':
    if len(sys.argv) == 4:
        firstrun = int(sys.argv[1])
        lastrun = int(sys.argv[2])
        flag = int(sys.argv[3])
        print("Copy data runno from {} to {}. Flag={}".format(
            firstrun, lastrun, flag))
        CopyEventdata(firstrun, lastrun, flag)
    elif len(sys.argv) == 5:
        firstrun = int(sys.argv[1])
        lastrun = int(sys.argv[2])
        flag = int(sys.argv[3])
        target = sys.argv[4]
        print("Copy data runno from {} to. Flag={}".format(
            firstrun, lastrun, flag))
        CopyEventdata(firstrun, lastrun, flag, target)
