"""
The MIT License (MIT)

Copyright (c) Serenity Software, LLC

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from cahoots.parsers.base import BaseParser
from cahoots.parsers.programming.lexer import ProgrammingLexer
from cahoots.parsers.programming.bayesian import ProgrammingBayesianClassifier
from cahoots.result import ParseResult
from SereneRegistry import registry
import os
import re
import glob
import yaml


class ProgrammingParser(BaseParser):
    """Determines if a sample of text is a programming language"""

    all_keywords = []
    language_keywords = {}

    @staticmethod
    def bootstrap(config):
        """Loads tokens from the yaml files on disk"""
        all_keywords = []
        language_keywords = {}

        directory = os.path.dirname(os.path.abspath(__file__))
        path = os.path.join(directory, "languages/*.yaml")

        for file_path in glob.glob(path):
            with open(file_path, 'r') as language_file:
                language = yaml.load(language_file)
                all_keywords.extend(language['keywords'])
                language_keywords[language['id']] = language

        registry.set('PP_all_keywords', set(all_keywords))
        registry.set('PP_language_keywords', language_keywords)

        ProgrammingBayesianClassifier.bootstrap(config)

    def __init__(self, config):
        BaseParser.__init__(self, config, "Programming", 0)
        self.all_keywords = registry.get('PP_all_keywords')
        self.language_keywords = registry.get('PP_language_keywords')

    # finding common words/phrases in programming languages
    def find_common_tokens(self, dataset):
        """Looking for any programming language keywords in the data"""
        return [keyword for keyword in dataset if keyword in self.all_keywords]

    @classmethod
    def basic_language_heuristic(cls, language_data, dataset):
        """Looking for specific programming language keywords in the data"""
        return [keyword for keyword in
                dataset if keyword in language_data['keywords']]

    @classmethod
    def create_dataset(cls, data):
        """Takes a data string and converts it into a dataset for analysis"""
        return set(re.split('[ ;,{}()\n\t\r]', data.lower()))

    @classmethod
    def normalize_scores(cls, data, lex_languages, bayes_languages):
        """Normalizing the parsing scores generated by lex and bayes parsing"""

        # Giving ourselves a maximum of 10% confidence
        # addition for lexer detection
        normalizer = 10 / float(
            max([scr for _, scr in lex_languages.items()])
        )
        normal_scores = {}

        for lang_id, score in lex_languages.items():
            normal_scores[lang_id] = (normalizer * score)

        # Pulling some stats out of our bayes
        # results so we can calculate a confidence
        results = [[lid, scr] for lid, scr in
                   bayes_languages.items() if lid in lex_languages]
        scores = [scr for lid, scr in results]
        min_score = min(scores)
        spread = max(scores) - min_score

        # We want to add up to 90% confidence based on the spread from min
        # to max matches Math for the actual normalization is explained in
        # a comment below
        if spread > 90:
            normalizer = 90.00 / spread
        else:
            normalizer = 1.00

        # Normalizing and assembling results
        for lang_id, score in results:

            # Example:
            #
            #     min_score = -1700
            #     score = -1500
            #     Therefore: score = -1500 + 1700 (200)
            #
            #     OR
            #
            #     min_score = -50
            #     score = -25
            #     Therefore: score = 25
            if min_score < -90:
                score = score + (-1 * min_score)
            else:
                score = -1 * score

            # Example:
            #     spread > 90 example:
            #         score = 210
            #         spread = 240 (ie: max of -1700 to min of -1940)
            #         normalizer = 90 / 240 = 0.375
            #         normalized score = 78.75
            #
            #     spread <= 90 example:
            #         score 25
            #         spread = 30
            #         normalizer = 1
            #         normalized score = 25
            normal_scores[lang_id] += (normalizer * score)

        # We reduce our confidence significantly
        # if the string provided is very short
        normalizer = (min(100, float(len(data))) / 100)
        if normalizer < 1:
            for lang_id in normal_scores:
                normal_scores[lang_id] = normal_scores[lang_id] * normalizer

        # turning the score into an integer
        for lang_id in normal_scores:
            normal_scores[lang_id] = int(round(normal_scores[lang_id]))

        return normal_scores

    def get_possible_languages(self, dataset):
        """
        Goes through each language's keywords and finds
        languages that share keywords with the provided data set
        """
        return [language for language, language_data in
                self.language_keywords.items() if
                self.basic_language_heuristic(
                    language_data, dataset
                )]

    def parse(self, data):
        """
        Determines if the data is an example of one of our trained languages
        """

        dataset = self.create_dataset(data)

        # Step 1: Is this possibly code?
        if not self.find_common_tokens(dataset):
            return

        # Step 2: Which languages match, based on keywords alone?
        matched_languages = self.get_possible_languages(dataset)

        # Step 3: Which languages match, based on a smarter lexer?
        lexer = ProgrammingLexer(matched_languages, data.lower())
        lex_languages = lexer.lex()

        if not lex_languages:
            return

        # Step 4: Using a Naive Bayes Classifier
        # to pinpoint the best language fits
        classifier = ProgrammingBayesianClassifier()
        bayes_languages = classifier.classify(data)

        scores = self.normalize_scores(data, lex_languages, bayes_languages)

        for lang_id, confidence in scores.items():
            yield ParseResult(self.type,
                              self.language_keywords[lang_id]['name'],
                              confidence)
