# -------------------------------------------------------------------------
#
#  Part of the CodeChecker project, under the Apache License v2.0 with
#  LLVM Exceptions. See LICENSE for license information.
#  SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#
# -------------------------------------------------------------------------

import json
import logging
import os

from typing import Dict, List

from codechecker_report_converter.report import File, get_or_create_file, \
    Report

from ..analyzer_result import AnalyzerResultBase


LOG = logging.getLogger('report-converter')


class AnalyzerResult(AnalyzerResultBase):
    """ Transform analyzer result of the ESLint analyzer. """

    TOOL_NAME = 'eslint'
    NAME = 'ESLint'
    URL = 'https://eslint.org/'

    def get_reports(self, file_path: str) -> List[Report]:
        """ Get reports from the given analyzer result. """
        reports: List[Report] = []

        if not os.path.exists(file_path):
            LOG.error("Report file does not exist: %s", file_path)
            return reports

        try:
            with open(file_path, 'r', encoding="utf-8", errors="ignore") as f:
                diagnostics = json.load(f)
        except (IOError, json.decoder.JSONDecodeError):
            LOG.error("Failed to parse the given analyzer result '%s'. Please "
                      "give a valid json file generated by ESLint.",
                      file_path)
            return reports

        file_cache: Dict[str, File] = {}
        for diag in diagnostics:
            file_path = os.path.join(
                os.path.dirname(file_path), diag.get('filePath'))

            if not os.path.exists(file_path):
                LOG.warning("Source file does not exists: %s", file_path)
                continue

            for bug in diag.get('messages', []):
                reports.append(Report(
                    get_or_create_file(
                        os.path.abspath(file_path), file_cache),
                    int(bug['line']),
                    int(bug['column']),
                    bug['message'],
                    bug['ruleId']))

        return reports
