/**
 * Created by wh on 2015/7/7.
 */
var co = require('co');
var bizCore = require('@gopalroy/biz-core');
var express = require('express');
var ApiHelper = require('./ApiHelper');
var debug = require('debug')('@gopalroy/test-drive');

var vehicleAPI = (function(){
    function VehicleAPI(){
        var router = new express();
        router.get('/', this.get);
        router.put('/', this.update);
        router.delete('/', this.remove);

        router.get('/status',this.getVehicleStatus);//获取一辆车的状态
        router.get('/pos',this.getVehiclePos); //获取一辆车的位置;

        this.router = router;
    }

    VehicleAPI.prototype.getRouter = function(){
        return this.router;
    };

    VehicleAPI.prototype.resolveVehicle = function(req, res, next){
        co(function*(){
            req.incar.vehicle = yield req.incar.testDrive.getVehicleByIdG(req.params.vehicleId);
            next();
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //查询
    VehicleAPI.prototype.get = function(req, res){
        res.json(req.incar.vehicle);
    };

    //修改
    VehicleAPI.prototype.update = function(req, res){
        co(function*(){
            var data = req.body;
            var vehicleNew = req.incar.vehicle;

            for(var k in data){
                if(data.hasOwnProperty(k)){
                    vehicleNew[k] = data[k]
                }
            }

            yield vehicleNew.updateG();
            res.json({status:'ok',vehicleNew:vehicleNew});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //删除
    VehicleAPI.prototype.remove = function(req, res){
        co(function*(){
            yield req.incar.testDrive.removeVehicleG(req.incar.vehicle);
            res.send({status:'ok'});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    //状态
    VehicleAPI.prototype.getVehicleStatus = function(req,res){
           co(function*(){
               var testDrive = req.incar.testDrive;
               var status = yield testDrive.getVehicleStatusG(req.incar.vehicle.id);
               res.send({status:'ok',vehicleStatus:status});
           }).catch(function(ex){
               debug(ex.stack);
               res.status(500).send(ex.stack);
           });
    };

    //位置
    VehicleAPI.prototype.getVehiclePos = function(req,res){
        co(function*(){
            var vehicleCtx = req.incar.vehicle;
            var pos = yield vehicleCtx.getVehiclePosG();
            res.send({status:'ok',vehiclePos:pos});
        }).catch(function(ex){
            debug(ex.stack);
            res.status(500).send(ex.stack);
        });
    };

    return VehicleAPI;
})();

module.exports = vehicleAPI;
