#!/usr/bin/env python

# Copyright (c) 2006 Bermi Ferrer Martinez
# bermi a-t bermilabs - com
#
# See the end of this file for the free software, open source license (BSD-style).

import re
from .base import Base

class Portuguese(Base):
    """
    Inflector for pluralize and singularize English nouns.

    This is the default Inflector for the Inflector obj
    """
    
    def __init__(self):
        super(Portuguese, self).__init__()
        
        self.uncountable_words = [
            'lapis', 'onibus', 'virus', 'caridade', 'bondade', 'fe', 'ouro', 'prata',
            'bronze', 'brisa', 'oxigenio', 'fome', 'sede', 'po', 'plebe', 'neve',
            'lenha', 'cristianismo', 'nazismo', 'sinceridade', 'lealdade', 'status'
        ]
        
        self.plural_irregular_words = {
            'bookmark': 'bookmarks',
            'direct': 'directs',
            'inbox': 'inboxes',
            'session': 'sessions',
            'fan': 'fans',
            'feed': 'feeds',
            'app': 'apps',
            'server': 'servers',
            'mediaserver': 'mediaservers',
            'streamer': 'streamers',
            'mal': 'males',
            'consul': 'consules',
            'mel': 'meis',
            'cal': 'cais',
            'aval': 'avais',
            'mol': 'mois',
            'til': 'tis',
            'projetil': 'projeteis',
            'facil': 'faceis',
            'dificil': 'dificeis',
            'fossil': 'fosseis',
            'cep': 'ceps',
            'log': 'logs',
            'banner': 'banners',
            'faq': 'faqs',
            'newsletter': 'newsletters',
            'vip': 'vips',
            'deploy': 'deploys',
            'mes': 'meses'
        }
        
        self.singular_irregular_words = {v: k for k, v in self.plural_irregular_words.items()}

    def add_uncountable_words(self, words):
        if not isinstance(words, list):
            words = [words]
        for word in words:
            if word not in self.uncountable_words:
                self.uncountable_words.append(word)

    def add_irregular_words(self, words_dict):
        for singular_word, plural_word in words_dict.items():
            self.plural_irregular_words[singular_word] = plural_word
            self.singular_irregular_words[plural_word] = singular_word

    def pluralize(self, word) :
        '''Pluralizes English nouns.'''

        rules = [
            ['r$', 'res'],
            ['m$', 'ns'],
            ['il$', 'is'],
            ['l$', 'is'],
            ['(ao)$', 'oes'],
            ['([aeiou])$', '\\1s']
        ]

        lower_cased_word = word.lower()

        for uncountable_word in self.uncountable_words:
            pattern = r'(?:^|[^a-z])' + uncountable_word + r'$'
            if re.search(pattern, lower_cased_word):
                return word

        for irregular in self.plural_irregular_words.keys():
            match = re.search('('+irregular+')$',word, re.IGNORECASE)
            if match:
                return re.sub(''+irregular+'$', match.expand('\\1')[0]+self.plural_irregular_words[irregular][1:], word, flags=re.IGNORECASE)

        for rule in range(len(rules)):
            match = re.search(rules[rule][0], word, re.IGNORECASE)
            if match :
                groups = match.groups()
                for k in range(0,len(groups)) :
                    if groups[k] == None :
                        rules[rule][1] = rules[rule][1].replace('\\'+str(k+1), '')

                return re.sub(rules[rule][0], rules[rule][1], word, flags=re.IGNORECASE)

        return word


    def singularize_word(self, word) :
        '''Singularizes English nouns.'''

        rules = [
            ['(ns)$', 'm'],
            ['([e][i]s)$', 'el'],
            ['(ais)$', 'al'],
            ['([i]s)$', 'il'],
            ['(oe)s$', 'ao'],
            ['(c)oes$', '\\1ao'],
            ['(r)es$', '\\1'],
            ['(z)es$', '\\1'],
            ['(s)es$', '\\1'],
            ['(le)ns$', '\\1n'],
            ['(de)ns$', '\\1n'],
            ['([aeou])is$', 'il'],
            ['([aeiou])s$', '\\1'],
            ['ns$', 'm'],
        ]

        lower_cased_word = word.lower()

        for uncountable_word in self.uncountable_words:
            pattern = r'(?:^|[^a-z])' + uncountable_word + r'$'
            if re.search(pattern, lower_cased_word):
                return word

        for irregular in self.singular_irregular_words.keys():
            match = re.search('('+irregular+')$',word, re.IGNORECASE)
            if match:
                return re.sub(''+irregular+'$', match.expand('\\1')[0]+self.singular_irregular_words[irregular][1:], word, flags=re.IGNORECASE)

        for rule in range(len(rules)):
            match = re.search(rules[rule][0], word, re.IGNORECASE)
            if match :
                groups = match.groups()
                for k in range(0,len(groups)) :
                    if groups[k] == None :
                        rules[rule][1] = rules[rule][1].replace('\\'+str(k+1), '')

                return re.sub(rules[rule][0], rules[rule][1], word, flags=re.IGNORECASE)

        return word

    def singularize(self, word):
        '''Singularizes each word'''
        words = word.split('_')
        words_done = []
        for word in words:
            words_done.append(self.singularize_word(word))
        return '_'.join(words_done)



# Copyright (c) 2006 Bermi Ferrer Martinez
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software to deal in this software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of this software, and to permit
# persons to whom this software is furnished to do so, subject to the following
# condition:
#
# THIS 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 THIS SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THIS SOFTWARE.
