# Copyright (c) 2017, John Skinner
import sys
import bson.objectid
import cv2
import numpy as np
import config.global_configuration as global_conf
import database.client
import core.image_collection
import core.image_entity


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:
    """
    if len(args) >= 1:
        image_source_id = bson.objectid.ObjectId(args[0])

        config = global_conf.load_global_config('config.yml')
        db_client = database.client.DatabaseClient(config=config)

        image_source = None
        s_image_source = db_client.image_source_collection.find_one({'_id': image_source_id})
        if s_image_source is not None:
            image_source = db_client.deserialize_entity(s_image_source)
        del s_image_source

        if image_source is not None:
            image_source.begin()
            while not image_source.is_complete():
                image, _ = image_source.get_next_image()
                debug_img = image.data[:, :, ::-1].copy()
                for obj in image.metadata.labelled_objects:
                    x, y, w, h = obj.bounding_box
                    cv2.rectangle(debug_img, (x, y), (x + w, y + h), (0, 0, 255), 2)

                    text_label = str(obj.class_names[0])
                    (retval, baseLine) = cv2.getTextSize(text_label, cv2.FONT_HERSHEY_COMPLEX, 1, 1)
                    text_org = (x, y - 0)

                    cv2.rectangle(debug_img, (text_org[0] - 5, text_org[1] + baseLine - 5),
                                  (text_org[0] + retval[0] + 5, text_org[1] - retval[1] - 5), (0, 0, 0), 2)
                    cv2.rectangle(debug_img, (text_org[0] - 5, text_org[1] + baseLine - 5),
                                  (text_org[0] + retval[0] + 5, text_org[1] - retval[1] - 5), (255, 255, 255), -1)
                    cv2.putText(debug_img, text_label, text_org, cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 0), 1)

                cv2.imshow('debug', debug_img)
                cv2.waitKey(0)


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