from xml.dom.minidom import parse
import argparse
import glob
import os

from ada.io.file_manager import FileManager
from ada.database_utils.fetch_files import fetch_from_acti


def main():
    """Synchronize actigraphic and PSG recordings. Usable only with PSG in OBCI format. Use with -h or --help for details."""
    parser = argparse.ArgumentParser(description="Cut beginings of actigraphic recordings to synchronize with PSG stages.", add_help=False)
    parser.add_argument('--files', '-f', nargs='+', type=str, required=True, help="Path to raw files.")
    parser.add_argument('--outdir', '-o', type=str, required=True, help="Directory in which trimmed files will be saved.")
    parser.add_argument('--xmldir', '-x', type=str, required=True, help="Directory with obci.xml files.")
    namespace = parser.parse_args()

    if len(namespace.files) == 1:
        files_to_work = glob.glob(namespace.files[0])
    else:
        files_to_work = namespace.files

    os.makedirs(namespace.outdir, exist_ok=True)

    for file in files_to_work:
        filename = os.path.basename(file).split('.')[0]
        outfile = os.path.join(namespace.outdir, filename + '.ada')
        if os.path.exists(outfile):
            print('File already exists, skipping', outfile)
            continue

        acti = FileManager.load_file(file)
        xml, _ = fetch_from_acti(file, namespace.xmldir, '', False)
        xml_dom = parse(xml)
        psg_start_ts = float(xml_dom.getElementsByTagName("rs:firstSampleTimestamp")[0].childNodes[0].data)
        acti = acti.cut_by_timestamp(psg_start_ts, None)
        FileManager.export_generic(outfile, acti)
        

        
if __name__ == '__main__':
    main()
