import json

from Application.Analyzer import Analyzer
from Application.Config.Parser import Parser
from Component.Debug.Debugger import Debugger
from Component.File.Finder import Finder
from Component.Output.CliOutput import CliOutput
from Report.ReporterFactory import ReporterFactory
from Report.ReporterInterface import ReporterInterface


class Application:
    def run(self, argv) -> None:
        output = CliOutput()

        # issues and debug
        debugger = Debugger(output).enable()

        config = Parser().parse(argv)

        finder = Finder()
        files = finder.fetch(config.project_configs)

        for project_config in config.project_configs:
            debugger.debug(project_config.name)
            project_files = files[project_config.name]
            debugger.debug(f"Found {len(project_files)} files")
            debugger.debug(json.dumps(project_files))

            output.writeln(f"<info>Analying Project {project_config.name}...</info>")
            project_metrics = Analyzer(project_config, output, debugger).run(
                project_files
            )
            output.writeln(
                f"<success>Done analying Project {project_config.name}</success>"
            )

            if not project_config.reports:
                output.writeln(
                    f"<success>Skipping reports of {project_config.name}!</success>"
                )
                continue

            output.writeln(
                f"<info>Generating reports for {project_config.name}...</info>"
            )
            for report_config in project_config.reports:
                reporter: ReporterInterface = ReporterFactory.create(
                    report_config, output
                )
                reporter.generate(project_metrics)
            output.writeln(
                f"<success>Reports generated for {project_config.name}</success>"
            )
