const configs = require("../configs");
const Library = require("../library");
const DeviceModel = require("../models/device.model");
const fetch = require("node-fetch");

const set = async (
  token,
  device_id,
  remote_name,
  remote_type,
  operating_type
) => {
  if (token === configs.verifyToken) {
    try {
      const deviceExist = await DeviceModel.findOne({
        _id: device_id
      });
      if (deviceExist) {
        const hostname = deviceExist.device_ip_address;
        const response = await fetch(
          "http://" +
            hostname +
            "/" +
            operating_type +
            "?token=" +
            configs.verifyToken
        );

        const isOpen = await response.text();
        console.log(isOpen);
        if (isOpen === "true") {
          Library.saveDeviceLog(
            device_id,
            remote_name,
            remote_type,
            operating_type
          );
          return operating_type + " işlemi başarılı!";
        } else {
          throw new Error("Client message: " + isOpen);
        }
      } else {
        throw new Error("Cihaz bulunamadı!");
      }
    } catch (error) {
      throw new Error(error.message);
    }
  } else {
    throw new Error("Hatalı token (set.controller)");
  }
};

module.exports = { set };
