/*
* Function correcting ordinal numbers:
* "1rd" --> "1st"
*/

module.exports = function (ruleManager, sentence, result) {

    if (!ruleManager || !result || !result.tokenIndices || result.tokenIndices.length < 1 || !sentence) {
        debugger;
        console.error("inputs are wrong");
        return false;
    }

    if (result.tokenRules.length < 1) {
        return false;
    }

    let number = sentence.tokens[result.tokenRules[0].tokenIndices[0]].word;

    if (!number){
        debugger;
        return false;
    }

    let numberIndex = result.tokenRules[0].tokenIndices[0];
    // var re_letters = /([a-z]){2}/;

    //var two_letters = number.match(re_letters);
    let two_letters = number.substr(number.length-2,number.length-1);
    // console.log("two_letters : " + two_letters);

    let onlyNumbers = number.substr(0,number.length-2);
    console.log("onlyNumbers : " + onlyNumbers);

    var dico_cardinalNumbers = ruleManager.dictionaries.ordinal_numbers_digits_with_end_letters;

    if (!dico_cardinalNumbers) {
        debugger;
        return false;
    }

    let numberOfDigits = onlyNumbers.length;
    let keyDigit = null;
    let suffixEnding = null;

    if (numberOfDigits>=2){
        keyDigit = onlyNumbers.substr(numberOfDigits-2,2);
        // console.log("keyDigit : " + keyDigit);
        for (var key in dico_cardinalNumbers) {
            if (keyDigit === key) {
                suffixEnding = dico_cardinalNumbers[key].suffix;
                // console.log("suffixEnding : " + suffixEnding);
                if (two_letters === suffixEnding){
                    // debugger;
                    return false;
                }

                two_letters=suffixEnding;
                //debugger;
                break;
            }
        }

    }

    else{
        keyDigit = onlyNumbers;
        for (var key in dico_cardinalNumbers) {
            if (keyDigit === key) {
                suffixEnding = dico_cardinalNumbers[key].suffix;
                // console.log("suffixEnding : " + suffixEnding);
                if (two_letters === suffixEnding){
                    debugger;
                    return false;
                }

                two_letters=suffixEnding;
                
                // debugger;
                break;
            }
        }
    }
    let compound_noun = onlyNumbers.concat(two_letters);
    console.log("compound_noun : " + compound_noun);

    var correction = {
        "type": "replaceAttValue",
        "suggestionIndice": 0,
        "att": "lemma",
        "text": compound_noun,
        "tokenIndice": numberIndex
    };

    ruleManager.AddCorrection(result, 0, correction);

    var correction = {
        "type": "replaceAttValue",
        "suggestionIndice": 0,
        "att": "word",
        "text": compound_noun,
        "tokenIndice": numberIndex
    };

    ruleManager.AddCorrection(result, 0, correction);

    return true;
    
};