import * as layerFuncs from './layers';
import request from 'superagent';
import zlib from 'zlib';
import concat from 'concat-stream';

export default class NeuralNet {
  constructor(config) {
    config = config || {};

    this.ARRAY_TYPE = (typeof Float64Array !== 'undefined') ? Float64Array : Array;
    this.SIMD_AVAIL = (this.ARRAY_TYPE === Float64Array) && ('SIMD' in this);
    this.WEBGL_AVAIL = true;

    if (typeof window !== 'undefined') {
      this.environment = 'browser';
    } else {
      this.environment = 'node';
    }

    this.readyStatus = false;
    this._layers = [];

    this.modelFile = config.modelFile || null;
    if (this.modelFile) {
      this.loadModel(this.modelFile);
    } else {
      throw new Error('no modelFile specified in config object.');
    }
  }

  loadModel(modelFile) {
    if (this.environment === 'node') {
      let gunzip = zlib.createGunzip();
      fs.createReadStream(__dirname + modelFile)
        .pipe(gunzip)
        .pipe(concat((model) => {
          this._layers = JSON.parse(model.toString());
          this.readyStatus = true;
        }));
    } else {
      let gunzip = zlib.createGunzip();
      request.get(`/${modelFile}`)
        .end((err, res, body) => {
          if (err) return console.error('error loading model file.');
          if (res.statusCode == 200) {
            this._layers = JSON.parse(body.toString());
            this.readyStatus = true;
          } else {
            console.error('error loading model file.');
          }
        });
    }
  }

  predict(input) {
    let X = input;

    if (!this.readyStatus) {
      let waitReady = setInterval(() => {
        if (this.readyStatus) {
          clearInterval(waitReady);
        }
      }, 10);
    }

    for (let layer of this._layers) {
      let { layerName, parameters } = layer;

      X = layerFuncs[layerName](X, ...parameters);
    }

    return X;
  }

}

@@ -590,16 +590,36 @@
  = %5B%5D;%0A%0A
+    // json or gzip%0A
     this
@@ -628,16 +628,20 @@
 odelFile
+Type
  = confi
@@ -651,16 +651,78 @@
 odelFile
+Type %7C%7C 'json';%0A%0A    this.modelFilePath = config.modelFilePath
  %7C%7C null
@@ -737,32 +737,36 @@
  (this.modelFile
+Path
 ) %7B%0A      this.l
@@ -788,16 +788,20 @@
 odelFile
+Path
 );%0A    %7D
@@ -843,16 +843,20 @@
 odelFile
+Path
  specifi
@@ -911,16 +911,20 @@
 odelFile
+Path
 ) %7B%0A    
@@ -1045,16 +1045,20 @@
 odelFile
+Path
 )%0A      
@@ -1233,75 +1233,82 @@
     
-let gunzip = zlib.createGunzip();%0A      request.get(%60/$%7BmodelFile%7D%60
+request.get(modelFilePath)%0A        .set('Content-Type', 'application/json'
 )%0A  
@@ -1331,14 +1331,8 @@
  res
-, body
 ) =%3E
@@ -1474,35 +1474,16 @@
 s = 
-JSON.parse(body.toString())
+res.body
 ;%0A  

update NeuralNet class data loading process