import os

from parallels.core import MigratorInterruptException
from parallels.core.registry import Registry
from parallels.core.utils.common import open_no_inherit
from parallels.core.utils.migrator_utils import get_optional_option_value


class StopMark(object):
    """Way to control shutdown of migrator. If set then migrator will try to shut down as soon as possible"""

    @classmethod
    def set(cls):
        stop_file = cls.get_stop_file_path()
        if stop_file is None:
            return

        with open_no_inherit(stop_file, 'w'):
            pass

    @classmethod
    def is_set(cls):
        stop_file = cls.get_stop_file_path()
        if stop_file is None:
            return False

        return os.path.isfile(stop_file)

    @classmethod
    def remove(cls):
        stop_file = cls.get_stop_file_path()
        if stop_file is None:
            return False
        os.remove(stop_file)

    @classmethod
    def get_stop_file_path(cls):
        context = Registry.get_instance().get_context()
        if context is None:
            return None

        cli_option = get_optional_option_value(context.options, 'stop_mark_file', None)

        if cli_option is not None:
            return cli_option

        session_files = context.session_files
        if session_files is None:
            return None

        return session_files.get_default_stop_mark_file()


def check_stop_mark(stop_mark):
    """
    :type stop_mark: parallels.core.utils.stop_mark.StopMark | None
    :raises: parallels.core.MigratorInterruptException 
    """
    if stop_mark is not None and stop_mark.is_set():
        raise MigratorInterruptException()
