# -------------------------------------------------------------------------
#
#  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 logging
import os
import json

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 TSLint analyzer. """

    TOOL_NAME = 'tslint'
    NAME = 'TSLint'
    URL = 'https://palantir.github.io/tslint'

    def get_reports(self, result_file_path: str) -> List[Report]:
        """ Parse 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 report_f:
                bugs = json.load(report_f)
        except (IOError, json.decoder.JSONDecodeError):
            LOG.error("Failed to parse the given analyzer result '%s'. Please "
                      "give a valid json file generated by TSLint.",
                      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('name'))

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

            end_pos = bug['startPosition']
            line = int(end_pos['line'] + 1)
            col = int(end_pos['character'] + 1)

            reports.append(Report(
                get_or_create_file(os.path.abspath(file_path), file_cache),
                line, col, bug['failure'], bug['ruleName']
            ))

        return reports
