const express = require('express');
const router = express.Router();
const fs = require('fs');

var cacheData;
const TENSE = {
    UNKNOWN: -1,
    PAST: 0,
    PRESENT: 1,
    FUTURE: 2,
    FORMAL: 3
}


router.post('/', async (req, res) => {

    try {
		
		// IMPORTANT - When you send the sentence you must have a shape. - ex: [subject] [object] [verb]

        var inputText = req.body.inputText;
        var requestedTense = req.body.tense;
        var selectedTense, subIndex = 0, correctVerb, outputText = '', sub, vrb;


        if(!cacheData) cacheData = JSON.parse(fs.readFileSync('./modules/dataset.json', 'utf8'));

        // convert input string to an array
        var sentenceArr = inputText.split(" ");

        // spell checker
        for(var [idx, val] of sentenceArr.entries()){
            // change value for subject
            if(cacheData.spellChecker.hasOwnProperty(val)){

                sentenceArr[idx] = cacheData.spellChecker[val];
            }
                
        }

        // pick subject and verb
        
        //find the subject
        for(var [idx, val] of sentenceArr.entries()){

            // find the subject and verb
            if(!val.includes("ට")){

                subIndex = cacheData.subject_sindular[val];
                

                if(typeof subIndex === "undefined") subIndex = getSubIndexByGender(val);
        
                if(typeof subIndex === "undefined") 
                    continue;

                sub = val;
                outputText += sub + ",";
                //break;
            }
        }

       if(outputText.split(',').length === 2){
        outputText = outputText.slice(0, -1) 
        subIndex = cacheData.subject_sindular[outputText];
        if(typeof subIndex === "undefined") subIndex = getSubIndexByGender(outputText);
       }
        

        vrb = sentenceArr[sentenceArr.length - 1];

        // detect the requested tense
        switch(requestedTense){
            case TENSE.PAST: selectedTense = "past"; break;
            case TENSE.PRESENT: selectedTense = "present"; break;
            case TENSE.FUTURE: selectedTense = "future"; break;
            case TENSE.FORMAL: selectedTense = "formal"; break;
            default : selectedTense = "unknown"; break;
        }

        if(selectedTense === "unknown")
            throw "Tense Not Found";

        if(requestedTense !== TENSE.FORMAL){

            if(outputText.includes(",")){
                correctVerb = cacheData.verbs[vrb][selectedTense][1];
                let subList = outputText.split(",");

                subList.forEach(s => {
                    sentenceArr.forEach((ss, idx) => {
                        if(s === ss)
                            sentenceArr[idx] = ss + ","
                    })
                })
            }  
            else{
                // get the relevent verb depending on the tense
                correctVerb = cacheData.verbs[vrb] ? cacheData.verbs[vrb][selectedTense][subIndex] : undefined;

                if(typeof correctVerb === 'undefined')
                    for(var [i, v] of sentenceArr.entries()){
                        correctVerb = cacheData.verbs[v] ? cacheData.verbs[v][selectedTense][subIndex] : undefined;
                        if(correctVerb)
                            break;
                    }
            }


            if(typeof correctVerb === "undefined") throw "Verb Not Found";

            // assemble the correct sentense
            // remove the input verb
            if(typeof i !== 'undefined')
                delete sentenceArr[i];
            else
                sentenceArr.pop();

            sentenceArr.push(correctVerb);

            
        }
        // formal
        else{

            if(outputText.includes(",")){
                // correctVerb = cacheData.verbs[vrb][selectedTense][1];
                let subList = outputText.split(",");

                subList.forEach(s => {
                    sentenceArr.forEach((ss, idx) => {
                        if(s === ss)
                            sentenceArr[idx] = ss + ","
                    })
                })
            }

            // convert the subject
            var formalSub = cacheData.formalSubList[sub];

            // convert the verb
            var formalVerb = cacheData.formalVerbList[vrb];

            if(typeof formalVerb === 'undefined')
                for(var [i, v] of sentenceArr.entries()){
                    formalVerb = cacheData.formalVerbList[v];
                    if(formalVerb)
                        break;
                }

            if(typeof formalVerb === "undefined") throw "Formal verb Not Found";

            // convert nouns
            for(var [idx, val] of sentenceArr.entries()){
                // change value for subject
                if(cacheData.formalNounList.hasOwnProperty(val)){
                    if(idx === 0)
                        sub = cacheData.formalNounList[val];

                    sentenceArr[idx] = cacheData.formalNounList[val];
                }
               
            }

            // compose the formal sentense
            var subIdx = sentenceArr.indexOf(sub);
            if(formalSub){
                if(subIdx !== -1) 
                    sentenceArr[subIdx] = formalSub;
            }
            else 
                sentenceArr[subIdx] = sentenceArr[subIdx];


            var vrbIdx = sentenceArr.indexOf(v);
            
            if(formalVerb){
                if(vrbIdx !== -1)
                    delete sentenceArr[vrbIdx];
                else
                    sentenceArr.pop();

                    sentenceArr.push(formalVerb);
            }
            else
                throw "Verb Not Found"

            sentenceArr.push(cacheData.formalEndWord);

        }

        // genarate the output
        // for(var [idx, sentense] of sentenceArr.entries()){

        //     if(outputText.includes(sentense))
        //         continue;
        //     outputText += " " + sentense;
        // }

        // // remove the last space
        // var outPutArr = outputText.split(" ");
        // outPutArr.pop();
        // outPutArr[outPutArr.length - 1] = correctVerb;


        outputText = sentenceArr.join(" ");
        outputText += ".";

        res.status(200).send(outputText);

    }
    catch(err) {
        res.status(500).send(err);
    }

});

// router.post('/getSuggestedWords', async(req, res, next) => {


//     try{

//         if(!cacheData) cacheData = JSON.parse(fs.readFileSync('./modules/dataset.json', 'utf8'));

//         var ltr = req.body.letters;

//         var dataSet = cacheData.wordSud[ltr];

//         if(dataSet)
//             res.status(200).send(dataSet);
//         else
//             res.status(200).send([]);

//     }
//     catch(e){
//         res.status(500).send(e);
//     }



// })

function getSubIndexByGender(subject){

    // female
    var isFemale = cacheData.subject_sindular["ගැහැණු"].includes(subject);
    if(isFemale) return 2;
 
    // male
    var isMale = cacheData.subject_sindular["පිරිමි"].includes(subject);
    if(isMale) return 3;

    // other
    var isOther = cacheData.subject_sindular["සර්වනාම"].includes(subject);
    if(isOther) return 3;

    return undefined;

}

module.exports = router;