/**
 * Created by leglars on 2017/5/9.
 */
var express = require('express');
var firebase = require('firebase');
var request = require('request');
var Particle = require('particle-api-js');
// var debounce = require('lodash.debounce');
var Rx = require('rxjs/Rx')


// Initialize Firebase
var config = {
    apiKey: "AIzaSyCiMNYzF8kk7H6IfVmGEMspJGJ5tEUycmI",
    authDomain: "wakeup-1da7c.firebaseapp.com",
    databaseURL: "https://wakeup-1da7c.firebaseio.com",
    projectId: "wakeup-1da7c",
    storageBucket: "wakeup-1da7c.appspot.com",
    messagingSenderId: "314436561282"
};
firebase.initializeApp(config);

// setup the basic info for connecting particle cloud
var particle = new Particle();
var token;
var DEVICE_ID = "420036000447353138383138";
var VARIABLE = "pressure";


particle.login({username:'leglars@gmail.com', password:'1936887IWMzy'}).then(
    function(data){
        token = data.body.access_token;
    },
    function(err) {
        console.log('Could not log in.', err);
    }
);


// start the express app
var database = firebase.database();
var app = express();

app.get("/", function(req, res) {
    res.send("Hello World");
    // database.ref("test/from/backend").set({
    //     "hello": "world"
    // })
});

app.get("/devicedata", function(req, res){
    
    var userInfo = {
        userId: req.query.userId,
        userSteps: Number(req.query.userSteps) || 30,
        userWeight: Number(req.query.userWeight) || 1500,
        date: getDate(),
    }

    function getDate() {
        var today = new Date();
        var dd = today.getDate();
        var mm = today.getMonth()+1; //January is 0!
        var yyyy = today.getFullYear();

        if(dd<10) {
            dd='0'+dd
        } 
        if(mm<10) {
            mm='0'+mm
        }
        return yyyy + "-" + mm + "-" + dd
    }

    res.send("start updating data ...");
    console.log(userInfo)
    /**
     * stop: when get a value from isWakeup, so the loop can stop
     * excuate: a loop: every 300ms request the pressure data from particle cloud
     *  -> push the data into function validSteps and get bool return
     *  -> push this record to firebase
     * 
     *  firebase structure
     *  userID
     *     # [Date]
     *        ## stepRecord - update from backend
     *           ### record
     *        ## steps - update from backend
     *        ## isWakeup - update from ios
     *     # userInfo
     *        ## ...
     */
    var steps = 0;
    var _data = []
    console.log("go into data")
    var getPressureValueFromSensor = setInterval(function(){
        Rx.Observable.fromPromise(
            particle.getVariable({
                deviceId: DEVICE_ID,
                name: VARIABLE,
                auth: token
            }))
        .subscribe({
            next: function(data) {
                var d = Number(data.body.result);
                console.log(d);
                pushDataAndCheckStep(d);
            },
            error: function(err) {
                console.log("error happened: " + err)
            },
            complete: function() {
                console.log("complete")
            }
        })

    if(steps === userInfo.userSteps) {
            clearInterval(getPressureValueFromSensor);
            console.log("stop the loop");
        }
    }, 300)

    function pushDataAndCheckStep(d) {
        _data.push(d);
        console.log("push data");
        if (checkStep(_data, d)) {
            updateSteps()
        };
    }

    function cleanData() {
        _data = [];
    }

    function updateSteps() {
        steps ++;
        updateFBStep(steps);
        console.log("steps: " + steps)
    }

    function checkStep(data, d) {
        console.log("check step" + "//////  data:  / " + data);
        if (Math.min.apply(null, data) < userInfo.userWeight / 2) {
            console.log("check step" + "#####  d: " + d);
            if (d > userInfo.userWeight * (1 - 0.2)) {
                setStepRecord(d);
                cleanData();
                console.log('step')
                return true
            }
        }
        return false
    }

    function setStepRecord(d) {
        database.ref(userInfo.userId + "/"
                     + userInfo.date + "/stepRecord")
                     .push(d)
    }

    function updateFBStep(step) {
        var updateStep = {}
        updateStep[userInfo.userId + "/" + userInfo.date + "/steps"] = step
        database.ref().update(updateStep)
    }
});

app.listen(3000, function() {
    console.log('example app listening on port 3000! Happy Hacker')
});

@@ -1083,26 +1083,27 @@
 ess();%0A%0Aapp.
-ge
+pos
 t(%22/%22, funct
@@ -1232,16 +1232,110 @@
   // %7D)%0A
+    console.log(%22you reach a new place%22)%0A    %0A    console.log(req)%0A    console.log(req.query)%0A
 %7D);%0A%0Aapp
@@ -1335,18 +1335,19 @@
 );%0A%0Aapp.
-ge
+pos
 t(%22/devi
@@ -1433,16 +1433,27 @@
 y.userId
+ %7C%7C %22chenx%22
 ,%0A      
@@ -1497,17 +1497,16 @@
 ps) %7C%7C 3
-0
 ,%0A      
@@ -1554,17 +1554,16 @@
 ) %7C%7C 150
-0
 ,%0A      
@@ -1574,18 +1574,65 @@
 te: 
-getDate(),
+req.query.date %7C%7C getDate(),%0A        uuid: req.query.uuid
 %0A   
@@ -2389,24 +2389,49 @@
  *        ##
+uuid%0A        *        ###
  stepRecord 
@@ -2444,32 +2444,35 @@
 te from backend%0A
+   
      *          
@@ -2479,16 +2479,17 @@
  ###
+#
  record%0A
     
@@ -2484,16 +2484,19 @@
  record%0A
+   
      *  
@@ -2503,16 +2503,17 @@
       ##
+#
  steps -
@@ -2534,24 +2534,27 @@
 ackend%0A     
+   
 *        ## 
@@ -2552,16 +2552,17 @@
       ##
+#
  isWakeu
@@ -4422,24 +4422,46 @@
 rInfo.date +
+ %22/%22 + userInfo.uuid +
  %22/stepRecor
@@ -4615,24 +4615,45 @@
 serInfo.date
++ %22/%22 + userInfo.uuid
  + %22/steps%22%5D

connect with ios by http