const OpenAI = require("openai");

var request = require('request');
const axios = require("axios")
const { response } = require('express');
const chatGPTKey = "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"
const client = new OpenAI({
  apiKey: chatGPTKey
});

async function chatTest(responseData) {
    var contentChat = responseData.webhook_event.body;
  if (contentChat.indexOf("[toall]") < 0) {
    var indexPicStart = contentChat.indexOf("image:");
    if (indexPicStart >=0) {
      //photo gener
      var promptText = contentChat.substring(indexPicStart + "image:".length, contentChat.length);
      console.log("prompt: "+ promptText);

      axios.post("https://api.openai.com/v1/images/generations", {
        prompt: promptText,
        n: 1,
        size: "512x512"
      },
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': "Bearer " + chatGPTKey,
        }
      }
      ).then(function(response) {
        console.log(response.data.data[0].url)
        chatmessage(responseData.webhook_event.room_id, responseData.webhook_event.from_account_id,
          responseData.webhook_event.message_id, response.data.data[0].url);  
      }).catch(function(error) {
        console.log(error)
      });

    } else {
      //chat
      var indexStart = contentChat.indexOf("[info]");
      var indexEnd = contentChat.indexOf("[/info]");
    var chatText = "";
      if (indexStart >= 0) {
        chatText = contentChat.substring(indexStart + "[info]".length, indexEnd);
      } else {
        chatText = contentChat.replace("[To:10088310][BSV] brave Assistant Bot","").replace("[To:10088310][BSV] brave Assistant Bot","");
      }
      console.log("Chat text: "+ chatText);
        const chatCompletion = await client.chat.completions.create({
          model: "gpt-4o-mini", //Set model ChatGPT
          messages: [{role: "user", content: chatText.trim()}],
        });
        chatmessage(responseData.webhook_event.room_id, responseData.webhook_event.from_account_id,
          responseData.webhook_event.message_id, chatCompletion.data.choices[0].message.content);  
    }
  }
  }

  async function test() {
    const chatCompletion = await client.chat.completions.create({
      model: "gpt-4o-mini",
      messages: [{role: "user", content: "Hello"}],
    });

    console.log("Chat text: "+ chatCompletion.data);
  }

  function chatmessage( _togroup, _touser,_messageid, _message){
    var formData = {
      // Pass a simple key-value pair
      body: "[rp aid="+_touser+" to="+_togroup+"-"+_messageid+"]\n"+_message
    }

    var _options = {
      method: 'POST',
      url: "https://api.chatwork.com/v2/rooms/"+_togroup+"/messages",
      formData: formData,
      headers: {
        'X-ChatWorkToken': '6f65b2cde85b3bb06dece173dc94d8cd', //Key chatwork
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    };

    request(_options, function(error, response, body){
      if (!error) {
        //var info = JSON.parse(body);
        console.log(body);
      }else{
        console.log(error);
      }
    });
}

function chatmessageTO( _togroup, formData ){  
var _options = {
method: 'POST',
url: "https://api.chatwork.com/v2/rooms/"+_togroup+"/messages",
formData: formData,
headers: {
'X-ChatWorkToken': '6f65b2cde85b3bb06dece173dc94d8cd',
'Content-Type': 'application/x-www-form-urlencoded'
}
};

request(_options, function(error, response, body){
if (!error) {
//var info = JSON.parse(body);
console.log(body);
}else{
console.log(error);
}
});
}


module.exports = function(app) {
    app.get('/', function(req, res, next){
      test()
        res.status(200).send({ success: true, message: 'success', data: "Welcome!"});
    });
    app.post('/test',  function(req, res, next) {
      var responseData = {
        //"webhook_setting_id" : req.body.webhook_setting_id,
        //"webhook_event_type" : req.body.webhook_event_type,
        //"webhook_event_time" : req.body.webhook_event_time,
        "webhook_event" : req.webhook_event,
    }
    var contentChat = responseData.webhook_event;
    //var indexStart = contentChat.indexOf("[info]") + "[info]".length;
    //var indexEnd = contentChat.indexOf("[/info]");
    var contentQuestion = contentChat;
    res.status(200).send({ success: true, message: 'success', data: "content :" + String(req)});
  });

  app.post('/user', function(req, res, next){
                var responseData = {
                    "webhook_setting_id" : req.body.webhook_setting_id,
                    "webhook_event_type" : req.body.webhook_event_type,
                    "webhook_event_time" : req.body.webhook_event_time,
                    "webhook_event" : req.body.webhook_event,
                }
                console.log("Request Data:", JSON.stringify(responseData, null, 2));
                console.log('dtest');
                //chatTest(responseData);
                console.log(responseData);
                res.status(200).send({ success: true, message: 'success', data: 'etes'});
        });

}
  
    