# -------------------------------------------------------------------------
#
#  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 ..output_parser import Message, BaseParser

LOG = logging.getLogger('ReportConverter')


class TSLintParser(BaseParser):
    """ Parser for TSLint output. """

    def parse_messages(self, analyzer_result):
        """ Parse the given analyzer result. """
        if not os.path.exists(analyzer_result):
            LOG.error("Report file does not exist: %s", analyzer_result)
            return

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

        for report in reports:
            file_path = os.path.join(os.path.dirname(analyzer_result),
                                     report.get('name'))
            if not os.path.exists(file_path):
                LOG.warning("Source file does not exists: %s", file_path)
                continue

            message = self.__parse_report(report, file_path)
            if message:
                self.messages.append(message)

        return self.messages

    def __parse_report(self, bug, file_path):
        """ Parse the given report and create a message from them. """
        checker_name = bug['ruleName']

        message = bug['failure']

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

        return Message(file_path, line, col, message, checker_name)
