# -------------------------------------------------------------------------
#
#  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 Pylint analyzer. """

    TOOL_NAME = 'pylint'
    NAME = 'Pylint'
    URL = 'https://www.pylint.org'

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

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

        try:
            with open(result_file_path, 'r',
                      encoding="utf-8", errors="ignore") as f:
                bugs = 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 Pylint.",
                      result_file_path)
            return reports

        file_cache: Dict[str, File] = {}
        for bug in bugs:
            file_path = os.path.join(
                os.path.dirname(result_file_path), bug.get('path'))
            if not os.path.exists(file_path):
                LOG.warning("Source file does not exists: %s", file_path)
                continue

            reports.append(Report(
                get_or_create_file(os.path.abspath(file_path), file_cache),
                int(bug['line']),
                int(bug['column']),
                bug['message'],
                bug['symbol']))

        return reports
