from contextlib import closing

from json import dumps, loads


class Result:
    """
    database class for results
    """

    def __init__(self, database, row):
        self.database = database

        self.identifier = row[0]
        self.file_id = row[1]
        self.origin = row[2]
        self.type = row[3]
        self.label = row[4]
        self.data = loads(row[5]) if row[5] is not None else None

    def file(self):
        """
        getter for the according file

        :return: file object
        """

        return self.database.file(self.file_id)

    def remove(self):
        """
        remove this result from the database

        :return:
        """
        with closing(self.database.con.cursor()) as cursor:
            cursor.execute('DELETE FROM results WHERE id = ?', [self.identifier])

    def set_origin(self, origin: str):
        """
        set this results origin

        :param origin: either 'user' or 'pipeline'
        :return:
        """
        with closing(self.database.con.cursor()) as cursor:
            cursor.execute('UPDATE results SET origin = ? WHERE id = ?', (origin, self.identifier))
            self.origin = origin

    def set_label(self, label: int):
        """
        set this results label

        :param label: label id
        :return:
        """
        with closing(self.database.con.cursor()) as cursor:
            cursor.execute('UPDATE results SET label = ? WHERE id = ?', (label, self.identifier))
            self.label = label

    def set_data(self, data: dict):
        """
        set this results data object

        :param data: data object
        :return:
        """
        if data is None:
            data_txt = None
        else:
            data_txt = dumps(data)

        with closing(self.database.con.cursor()) as cursor:
            cursor.execute('UPDATE results SET data = ? WHERE id = ?', (data_txt, self.identifier))
            self.data = data
