# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved.                     #
# This file is part of the AiiDA code.                                    #
#                                                                         #
# The code is hosted on GitHub at https://github.com/aiidateam/aiida_core #
# For further information on the license, see the LICENSE.txt file        #
# For further information please visit http://www.aiida.net               #
###########################################################################

from aiida.orm.implementation.calculation import Calculation
from aiida.common.lang import override
from aiida.common.links import LinkType

class WorkCalculation(Calculation):
    """
    Used to represent a calculation generated by a Process from the new
    workflows system.
    """
    FINISHED_KEY = '_finished'
    FAILED_KEY = '_failed'
    ABORTED_KEY = '_aborted'

    @override
    def has_finished(self):
        return self.has_finished_ok() or self.has_failed() or self.has_aborted()

    @override
    def has_finished_ok(self):
        """
        Returns True if the work calculation finished normally, False otherwise
        (could be that it's still running)

        :return: True if finished successfully, False otherwise.
        :rtype: bool
        """
        return self.get_attr(self.FINISHED_KEY, False)

    @override
    def has_failed(self):
        """
        Returns True if the work calculation failed because of an exception,
        False otherwise

        :return: True if the calculation has failed, False otherwise.
        :rtype: bool
        """
        return self.get_attr(self.FAILED_KEY, False)

    def has_aborted(self):
        """
        Returns True if the work calculation was killed and is

        :return: True if the calculation was killed, False otherwise.
        :rtype: bool
        """
        return self.get_attr(self.ABORTED_KEY, False)

    def kill(self):
        """
        Kill a WorkCalculation and all its children.
        """
        if not self.is_sealed:
            self._set_attr(self.ABORTED_KEY, True)

        for child in self.get_outputs(link_type=LinkType.CALL):
            child.kill()
