// Generated by CoffeeScript 2.3.1
// Import
var exec, extractOptsAndCallback, filterByInterface, getMac, isMac, isWindows, macRegex, zeroRegex;

({exec} = require('child_process'));

extractOptsAndCallback = require('extract-opts');

// Prepare
isWindows = process.platform.indexOf('win') === 0;

macRegex = /(?:[a-z0-9]{2}[:\-]){5}[a-z0-9]{2}/ig;

zeroRegex = /(?:[0]{2}[:\-]){5}[0]{2}/;

// Filter By Interface
// filterByInterface(iface, str)
filterByInterface = function(iface, str) {
  var i, len, line, lines, match, padding, result;
  iface = new RegExp(`${iface}[:\\s]`);
  lines = str.split(/\r?\n/g);
  result = '';
  padding = null;
  for (i = 0, len = lines.length; i < len; i++) {
    line = lines[i];
    if (result.length === 0) {
      if (iface.test(line)) {
        result += line;
      }
      continue;
    } else if (padding === null) {
      match = /^(\s+)/.exec(line);
      if (match) {
        result += `\n${line}`;
        padding = new RegExp(`^${match[1]}`);
        continue;
      }
    } else {
      match = padding.exec(line);
      if (match) {
        result += `\n${line}`;
        continue;
      }
    }
    break;
  }
  return result;
};

// Get Mac
// next(err,macAddress)
getMac = function(opts, next) {
  var command, data, extractMac, iface;
  // Prepare
  [opts, next] = extractOptsAndCallback(opts, next);
  ({data, iface} = opts);
  if (data == null) {
    data = null;
  }
  if (iface == null) {
    iface = null;
  }
  // Command
  command = isWindows ? "%SystemRoot%/System32/getmac.exe" : "/sbin/ifconfig -a || /sbin/ip link";
  // Extract Mac
  extractMac = function(data, next) {
    var err, isZero, macAddress, match, result;
    if (iface) {
      // Prepare
      data = filterByInterface(iface, data);
    }
    result = null;
    // Find a valid mac address
    while (match = macRegex.exec(data)) {
      macAddress = match[0];
      isZero = zeroRegex.test(macAddress);
      if (isZero === false) {
        if (result == null) {
          result = macAddress;
        }
      }
    }
    // We have no mac address so return an error
    if (result === null) {
      err = new Error('could not determine the mac address from:\n' + data);
      return next(err);
    }
    // Forward with result
    return next(null, result);
  };
  // If we already have data go straight to extracting the mac
  if (data) {
    return extractMac(data, next);
  } else {
    // Otherwise fetch the data first
    return exec(command, function(err, stdout, stderr) {
      if (err) {
        // Exit if error
        return next(err);
      }
      // Otherwise forward
      return extractMac(stdout, next);
    });
  }
};

// Is Mac
isMac = function(macAddress) {
  var ref;
  return ((ref = String(macAddress).match(macRegex)) != null ? ref.length : void 0) === 1;
};

// Export
module.exports = {macRegex, getMac, isMac};
