# -*- coding: utf-8 -*-
#
# Copyright (C) 2015 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>

import logging
import unicodedata
import re

logger = logging.getLogger()


class RaiseStopper(object):

    def __init__(self, return_on_raise):
        self.return_on_raise = return_on_raise

    def execute(self, function, *args, **kwargs):
        try:
            return function(*args, **kwargs)
        except Exception:
            logger.exception('An error occured in %s', function.__name__)
        return self.return_on_raise

def remove_diacritics(input_str):
    if not input_str:
        return u''
    else:
        text = input_str
        if not isinstance(text, unicode):
            text = unicode(text, 'utf-8')
        
        nkfd = unicodedata.normalize('NFKD', text)
        res = u"".join([c for c in nkfd if not unicodedata.combining(c)])
        return res

def normalize_term(input_str):
    return remove_diacritics(input_str).lower()

def normalize_array(arr):
    return [normalize_term(c) for c in arr if c]

def tokenize(input_str):
    splitted = re.split(' |-|\+|,', input_str)
    return normalize_array(splitted)

def terms_match_array(terms, unnormalized_array):
    normalized_array = normalize_array(unnormalized_array)
    for t in terms:
        if not any(t in s for s in normalized_array):
            return False
    return True
