const express = require('express');
const router = express.Router();
const dialogflow = require('dialogflow');
const AWS = require('aws-sdk');
fs = require('fs');
const config = require('../../config/digitalHuman/config');

// Configuring projectID, SessionID and Language code
const projectId = config.googleProjectID
const sessionId = config.dialogFlowSessionID
const languageCode = config.dialogFlowSessionLanguageCode

// Credentials for Amazon Polly
const Polly = new AWS.Polly({
    // Region of AWS polly service
    region: 'us-west-2',
    // AccesskeyID of AWS polly service
    accessKeyId: 'AKIAWJCX4TSYJQYA5O5H',
    // Secret Access Key
    secretAccessKey: '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'
})

// Credentials for dialogflow
const credentials = {
    // Client email of dialog flow
    client_email: config.googleClientEmail,
    // Private key of dialog flow
    private_key: config.googlePrivateKey
}

// Create a new session
const sessionClient = new dialogflow.SessionsClient({
    projectId, credentials
});
const sessionPath = sessionClient.sessionPath(projectId, sessionId);

router.post('/textQuery', async (req, res) => {
    const request = {
        session: sessionPath,
        queryInput: {
            text: {
                // The query to send to the dialogflow agent
                text: req.body.text,
                // The language used by the client (en-US)
                languageCode: languageCode,
            },
        },
    };

    // Send request and log result
    const responses = await sessionClient.detectIntent(request);
    console.log('Detected intent');
    const result = responses[0].queryResult;
    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);

    // voice initialization 
    const voice = {
        Text: result.fulfillmentText,
        OutputFormat: "mp3",
        VoiceId: "Joanna"
    }

    // Generating wav output
    Polly.synthesizeSpeech(voice, (err, data) => {
        if (err) {
            console.log(err)
            return
        }
        if (data.AudioStream instanceof Buffer) {
            fs.writeFile('voice_output.wav', data.AudioStream, (err) => {
                if (err) {
                    console.error(err)
                    return
                }
                console.log('Respond converted into wav file')
            })
        }
    }
    )

    //output as a text
    fs.writeFile('output.txt', result.fulfillmentText, function (err, data) {
        if (err) {
            return console.log(err);
        }
        console.log('Respond converted into text file')
    });
    res.send(result)
})

//Event Query Route

router.post('/eventQuery', async (req, res) => {
    const request = {
        session: sessionPath,
        queryInput: {
            event: {
                // The query to send to the dialogflow agent
                name: req.body.event,
                // The language used by the client (en-US)
                languageCode: languageCode,
            },
        },
    };

    // Send request and log result
    const responses = await sessionClient.detectIntent(request);
    console.log('Detected intent');
    const result = responses[0].queryResult;
    console.log(`  Query: ${result.queryText}`);
    console.log(`  Response: ${result.fulfillmentText}`);

    res.send(result)
}
)

module.exports = router;
