/* Copyright 2017-present Renesas Electronics Corporation and other contributors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

function Nic() {
}

function func_ifup(nic, param) {
  param = param || {};
  var dhcp = !param.ip || !param.netmask || !param.gateway;
  var obj = [];
  obj.push("dhcp:"); obj.push(dhcp ? "1" : "0");
  if(!dhcp) {
    if(param.ip)      { obj.push("ip:");      obj.push(param.ip); }
    if(param.netmask) { obj.push("netmask:"); obj.push(param.netmask); }
    if(param.gateway) { obj.push("gateway:"); obj.push(param.gateway); }
  }
  if(param.dns) { obj.push("dns:"); obj.push(param.dns); }
  if(param.wifi) {
    obj.push("wifi.ssid:");     obj.push(param.wifi.ssid     || "<SSID>");
    obj.push("wifi.password:"); obj.push(param.wifi.password || "<PASSWORD>");
    obj.push("wifi.security:"); obj.push(param.wifi.security || "<WEP/WPA/WPA2>");
    obj.push("wifi.ch:");       obj.push(param.wifi.ch       || 11);
  }
  return native.ifup(nic, obj.join('\n'));
}

function func_ifdown(nic) {
  return native.ifdown(nic);
}

function func_ifconfig(nic) {
  return JSON.parse(native.ifconfig(nic));
}

function func_ntpdate(nic, param) {
  param = param || {};
  var obj = {
    server : param.server  || "0.pool.ntp.org",
    port   : param.port    || 123,
    timeout: param.timeout || 10 * 1000,
  };
  return native.ntpdate(nic, obj);
}

Nic.prototype.enumerate = function() {
  var nics = JSON.parse(native.enumerate());
  Object.keys(nics).forEach(function(nic) {
    nics[nic].ifup = function(param) {
      return func_ifup(nic, param);
    };
    nics[nic].ifdown = function() {
      return func_ifdown(nic);
    };
    nics[nic].ifconfig = function() {
      return func_ifconfig(nic);
    };
    nics[nic].ntpdate = function(param) {
      return func_ntpdate(nic, param);
    };
  });
  return nics;
}

module.exports = new Nic();
module.exports.Nic = Nic;

