# -*- coding: utf-8 -*-
# Copyright (c) 2020-2022 Salvador E. Tropea
# Copyright (c) 2020-2022 Instituto Nacional de Tecnología Industrial
# License: GPL-3.0
# Project: KiBot (formerly KiPlot)
import os
from sys import exit
from .macros import macros, pre_class  # noqa: F401
from .error import KiPlotConfigurationError
from .gs import GS
from .kiplot import check_eeschema_do, exec_with_retry, add_extra_options
from .misc import CMD_EESCHEMA_DO, BOM_ERROR, kiauto_dependency
from .registrable import RegDependency
from .log import get_logger

logger = get_logger(__name__)
RegDependency.register(kiauto_dependency('update_xml'))


@pre_class
class Update_XML(BasePreFlight):  # noqa: F821
    """ [boolean=false] Update the XML version of the BoM (Bill of Materials).
        To ensure our generated BoM is up to date.
        Note that this isn't needed when using the internal BoM generator (`bom`) """
    def __init__(self, name, value):
        super().__init__(name, value)
        if not isinstance(value, bool):
            raise KiPlotConfigurationError('must be boolean')
        self._enabled = value
        self._sch_related = True

    def get_targets(self):
        """ Returns a list of targets generated by this preflight """
        return [GS.sch_no_ext+'.xml']

    def run(self):
        check_eeschema_do()
        out_dir = self.expand_dirname(GS.out_dir)
        cmd = [CMD_EESCHEMA_DO, 'bom_xml', GS.sch_file, out_dir]
        # If we are in verbose mode enable debug in the child
        cmd, video_remove = add_extra_options(cmd)
        # While creating the XML we run a BoM plug-in that creates a useless BoM
        # We remove it, unless this is already there
        side_effect_file = os.path.join(out_dir, GS.sch_basename+'.csv')
        remove_side_effect_file = not os.path.isfile(side_effect_file)
        logger.info('- Updating BoM in XML format')
        ret = exec_with_retry(cmd)
        if remove_side_effect_file and os.path.isfile(side_effect_file):
            os.remove(side_effect_file)
        if ret:
            logger.error('Failed to update the BoM, error %d', ret)
            exit(BOM_ERROR)
        if video_remove:
            video_name = os.path.join(self.expand_dirname(GS.out_dir), 'bom_xml_eeschema_screencast.ogv')
            if os.path.isfile(video_name):
                os.remove(video_name)
