# _create_action.py
#
# Project: AutoArchive
# License: GNU GPLv3
#
# Copyright (C) 2003 - 2023 Róbert Čerňanský



from AutoArchive._infrastructure.ui import VerbosityLevels
from .action_utils import ActionUtils
from ..._action.action_result import ActionResult
from ..._action.action import Action



class CreateAction(Action):

    def __init__(self, actionUtils: ActionUtils, selectedArchiveSpecs):
        super().__init__(actionUtils.actionResult)

        self.__actionUtils = actionUtils
        self.__selectedArchiveSpecs = selectedArchiveSpecs

        self.__commandExecutor = actionUtils.commandExecutor
        self.__componentUi = actionUtils.componentUi



    def executeAction_(self) -> bool:
        archiveSpecsForProcessing = self.__actionUtils.getArchiveSpecsForProcessing(self.__selectedArchiveSpecs)
        if archiveSpecsForProcessing is None:
            return False

        try:
            self.__commandExecutor.executeBeforeAllCommand()
        except OSError as ex:
            self.__componentUi.showError(ex.args[0])
            return False

        for specName, specFile in archiveSpecsForProcessing:
            processingArchSpec = specName or specFile
            self.__componentUi.setProcessingArchSpec(processingArchSpec)

            if self.__componentUi.verbosity == VerbosityLevels.Verbose:
                self.__componentUi.showVerbose(str.format("\nProcessing \"{}\"...", processingArchSpec))

            # create the archive
            self.__actionUtils.archiving.makeBackup(specFile)

        try:
            self.__commandExecutor.executeAfterAllCommand()
        except OSError as ex:
            self.__componentUi.showError(ex.args[0])
            return False

        self.__componentUi.setProcessingArchSpec(None)

        return True



    def handleResult_(self, actionResult: ActionResult) -> None:
        if self.__componentUi.verbosity == VerbosityLevels.Verbose:
            self.__componentUi.showVerbose("")
            if actionResult.result == ActionResult.ActionResults.Successful:
                self.__componentUi.showVerbose("Backup creation completed successfully.")
            elif actionResult.result == ActionResult.ActionResults.Issues:
                self.__componentUi.showVerbose("Backup creation completed successfully. One or more warnings were " +
                                               "shown. Check program's output for details.")
            else:
                self.__componentUi.showVerbose("Backup creation for one or more archives finished with error(s)! " +
                                               "Check program's output for details.")
