require("dotenv").config();
const { default: axios } = require("axios");
// LOGGING
const logger = require("../logger");
const { formResponse } = require("./../helpers/formResponse");
// HELPERS


// This function will send the Commands to the ONELAN NTB Device to skip to the Rendezvous point configured.
module.exports.sendPayload = async function (req, res) {
  try {
    let rendezvousName = req.params.rendezvous;

    let payload = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                      <command_list>
                          <advance_to rendezvous_name="${rendezvousName}" command_id="1"/>
                      </command_list>`;

    console.log('[NTB Controller] Sending Payload to NTB');
    console.log(payload)
    let configVal = {
      headers: { 'Content-Type': 'text/xml' },
      auth: {
        username: process.env.NTB_XMLUSER || 'xml_user',
        password: process.env.NTB_XMLPASS || 'xml'
      }
    };

    let myResult = await axios.post(`http://${process.env.NTB_IPADDRESS}/XML2`, payload, configVal);
    if (myResult) {
      console.log(myResult.data);
      return res.status(200).json(myResult.data);
    }
  } catch (err) {
    logger.error(err.message);
    return res.status(400).json(formResponse("error", null, err.message));
  }
};


// This function will send the Commands to the ONELAN NTB Device for PLI configuration.
module.exports.sendMultiPLIPayload = async function (req, res) {
  try {
    let pliName = req.body.pliName || 'hive_control';
    let pliVal = req.body.pliVal;

    async function iterPLIFormat(value) {

      let iterPli = '';
      // Iterate over the option values
      for (let i = 0; i < value.length; i++) {
        iterPli = iterPli + '<value>' + value[i] + '</value>';
      }
      return iterPli;
    }

    let myPLIValues = await iterPLIFormat(pliVal);


    let payload = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
                  <command_list>
                      <set_player_local_info command_id="cmd_local" name="${pliName}">
                          <data_player_local_info>
                              ${myPLIValues}
                          </data_player_local_info>
                      </set_player_local_info>
                  </command_list>`;

    let configVal = {
      headers: { 'Content-Type': 'text/xml' },
      auth: {
        username: process.env.NTB_XMLUSER || 'xml_user',
        password: process.env.NTB_XMLPASS || 'xml'
      }
    };
    let myResult = await axios.post(`http://${process.env.NTB_IPADDRESS}/XML2`, payload, configVal);
    if (myResult) {
      return res.status(200).json({ "message": "Success" });
    }
  } catch (err) {
    logger.error(err);
    return res.status(400).json(formResponse("error", null, err.message));
  }
};