from plone.memoize.view import memoize
from Products.Five import BrowserView
from tempfile import TemporaryDirectory

import logging

logger = logging.getLogger(__name__)


class CommandView(BrowserView):
    command = None
    arguments = []

    @memoize
    def get_tempdir(self):
        """Returns a temporary directory that will be cleaned after
        it is not needed anymore
        """
        return TemporaryDirectory(prefix="quaive")

    def is_needed(self):
        """Override this if you want to add some code that prevents
        the command to run (e.g. because you already ran it in the past)
        """
        return True

    def pre_command(self):
        """Things to do before you run the command"""

    def post_command(self):
        """Things to do after you run the command"""

    def run(self, force=False):
        if not force and not self.is_needed():
            return
        with self.get_tempdir():
            self.pre_command()
            result = self.command(*self.arguments, _return_cmd=True)
            logger.info(
                "The command %r terminated with exit code %r",
                result.ran,
                result.exit_code,
            )
            self.post_command()
