#!/usr/bin/env python3
import os
from tempfile import TemporaryDirectory

import caosdb as db
from caosadvancedtools.export_related import export_related_to
from caosadvancedtools.import_from_xml import import_xml

if __name__ == "__main__":
    print("Conducting im- and export tests")
    rec = db.execute_query("FIND 2019-02-03_really_cool_finding", unique=True)
    directory = TemporaryDirectory()
    export_related_to(rec.id, directory=directory.name)
    # delete everything
    print("Clearing database")
    recs = db.execute_query("FIND entity with id>99")
    recs.delete()
    assert 0 == len(db.execute_query("FIND File which is stored at "
                                     "**/poster.pdf"))
    print("Importing stored elements")
    import_xml(os.path.join(directory.name, "caosdb_data.xml"), interactive=False)

    # The following tests the existence of some required entities.
    # However, this is not a full list.
    db.execute_query("FIND 2019-02-03_really_cool_finding", unique=True)
    db.execute_query("FIND RecordType Poster", unique=True)
    db.execute_query("FIND RecordType Analysis", unique=True)
    db.execute_query("FIND RecordType Person", unique=True)
    db.execute_query("FIND Record Person with firstname=Only", unique=True)
    db.execute_query("FIND File which is stored at **/poster.pdf", unique=True)
    print("Found all required Records and Files.")
