import os

from calculation.errors import CalculationError

from task.states.base import TaskStateBase
from task.states.error import TaskErrorState
from task.states.ready import TaskReadyState


class TaskTearDownState(TaskStateBase):
    @property
    def name(self):
        return "tear down"

    def run(self):
        try:
            self._task.logger.info("Run tear down phase of calculation")
            self._task.calculation.tear_down()
            self.__delete_unpreserved_files()
            self._task.change_state(TaskReadyState(self._task))
        except CalculationError as calculation_error:
            self._task.logger.error("Calculation error occurred during tear down phase")
            self._task.logger.exception(calculation_error)
            self._task.change_state(TaskErrorState(self._task))

    def __delete_unpreserved_files(self):
        for obj in self._task.configuration.objects:
            if not obj.preserve and os.path.exists(obj.local):
                os.remove(obj.local)
