class IpHunter {
  constructor(ips, callback, timeout) {
    this.version="v2.0.1.20170819"
    this.ip = '';
    this.ipcallback = callback;
    this.timeoutId = null;
    this.reqsCache = [];

    for (let i = 0; i < ips.length; i++) {
      this.reqsCache.push(this.send(ips[i], timeout - 10));
    }
    this.timeoutId = setTimeout(this.notify.bind(this), timeout);
  }

  clearAll() {
    if (this.reqsCache && this.reqsCache.length) {
      this.reqsCache.forEach((req) => {
        req.abort();
      })
    }
    clearTimeout(this.timeoutId);
    this.ip = '';
    this.ipcallback = null;
    this.timeoutId = null;
    this.reqsCache = [];
  }

  clearReq(req) {
    this.reqsCache.splice(this.reqsCache.indexOf(req), 1);
  }

  notify() {
    if(this.ipcallback){
      this.ipcallback(this.ip);
    }
    this.clearAll();
  }

  send(pip, timeout) {
    const req = new XMLHttpRequest();
    req.open('HEAD', `//${pip}/?_=${Date.now()}`);
    req.timeout = timeout;
    req.onload = () => {
      this.ip = pip;
      this.clearReq(req);
      req.onload = null;
      this.notify();
    }
    req.ontimeout = () => {
      this.clearReq(req);
      req.ontimeout = null;
    }
    req.onerror = () => {
      this.clearReq(req);
      req.onerror = null;
    }
    req.onabort = () => {
      this.clearReq(req);
      req.onabort = null;
    }
    req.send();
    return req
  }
}

/**
 * ips check
 * @param  {array} ips
 * @param  {number} callback
 * @return {null}
 */
export default function check(ips, callback, timeout = 3000) {
  if (!(ips && ips.length && callback)) throw new Error('ips and callback are required.');
  new IpHunter(ips, callback, timeout);
}