import sys
import config.global_configuration as global_conf
import database.client
import database.entity_registry


def check_collection(collection, db_client):
    all_entities = collection.find()
    failures = []
    for s_entity in all_entities:
        # patch the entity type if appropriate
        if not '.' in s_entity['_type']:
            qual_types = database.entity_registry.find_potential_entity_classes(s_entity['_type'])
            if len(qual_types) == 1 and qual_types[0] != s_entity['_type']:
                failures.append("Entity {0} had unqualified type {1}".format(s_entity['_id'], s_entity['_type']))
                #collection.update({'_id': s_entity['_id']}, {'$set': {'_type': qual_types[0]}})

        # Try and deserialize the entity, and validate it if we succeed
        try:
            entity = db_client.deserialize_entity(s_entity)
        except Exception as e:
            failures.append(str(e))
        if entity is not None and hasattr(entity, 'validate') and entity.validate():
            failures.append("Entity {0} of type {1} failed to validate".format(s_entity['_id'], s_entity['_type']))

    for failure in failures:
        print(failure)


def main(*args):
    """
    Run a given system with a given image source.
    This represents a basic task.
    Scripts to run this will be autogenerated by the job system
    The first argument is the system id, the second argument is the image source to use
    (note that args[0] should be the x
    :return:
    """
    config = global_conf.load_global_config('config.yml')
    db_client = database.client.DatabaseClient(config=config)

    # Patch saved entity types to fully-qualified names
    check_collection(db_client.trainer_collection, db_client)
    check_collection(db_client.trainee_collection, db_client)
    check_collection(db_client.system_collection, db_client)
    check_collection(db_client.image_source_collection, db_client)
    check_collection(db_client.image_collection, db_client)
    check_collection(db_client.trials_collection, db_client)
    check_collection(db_client.benchmarks_collection, db_client)
    check_collection(db_client.results_collection, db_client)
    check_collection(db_client.experiments_collection, db_client)


if __name__ == '__main__':
    main(*sys.argv[1:])
