tanvirraj
10/9/2017 - 9:07 AM

s.js

import React from 'react';
import {Button,Checkbox} from 'semantic-ui-react';
import {observer, inject} from 'mobx-react';
import {refreshToken} from './../../helper/refresh-token';
import {observable, computed} from 'mobx';
import {alertMessage} from './../../helper/alert-message.js';
import {getData} from './../../helper/dataService.js';

function generateRoute(id, timeFrame){
  if(id!==undefined){
    let assetId = id.assetId;
    let start = timeFrame[0];
    let end = timeFrame[1];
    let url = `http://dev.finder-lbs.com:8000/assets/${assetId}/history_data?from=${start}&to=${end}&access_token=`;
    return getData(url);
  }
}

@inject("timer")
@observer
class Details extends React.Component{
    constructor(props){
      super(props);
      this.state ={
        name: 'DEFAULT',
        speed: 'No Limit',
        status: false,
        time: new Date().toString(),
        nlm: [],
        isFetchingAnim: false,
        isFetchingRoute: false,
        isRunning: false,
        engineStatus: true
      };
    }

    componentDidUpdate(prevProps, prevState){
      if (prevProps.id !== this.props.id && this.props.id!==-1) {
        var single = this.props.data[this.props.id];
        this.setState({
          name: single.key,
          speed: single.children[0].speed,
          time: single.children[2].time,
          nlm: single.children[3].nlm,
          status: single.children[4].active,
          engineStatus: false
        });
      }

      if(prevProps.animationRunning !== this.props.animationRunning){
        this.setState({
          isRunning: this.props.animationRunning
        });
      }
    }

    makeAnimation = (res) => {
      var temp = {};
      temp["children"] = [];
      var result =[];

      if(res.data.length){
        res.data.map((x,i) => {
          result.push({
            "key": i,
            "position": [x.loc.coordinates[1], x.loc.coordinates[0]] ,
            "children": [
              {"asset_type":"test"},
              {"name" :"test"},
              {"speed": x.speed},
              {"bearing" : x.bearing}
            ]
          })
        });
      }else{
        alertMessage('Sorry, unable to play your animation.');
        return;
      }
      return result;
    }

    startAnimation = (res) => {
      if(res.data.length){
        this.setState({isFetchingAnim: false});
        this.setState({isRunning: true});
        var result = this.makeAnimation(res);
        this.props.passAnimateData(result);
      }else{
        this.setState({isFetchingAnim: false});
        alertMessage('Sorry, no data found to play your animation.');
      }
    }

    animate = () => {
        var date = [this.props.timer.start, this.props.timer.end];
        if(date[0]!=='START TIME' || date[1]!=='END TIME'){
          var id = this.props.data[this.props.id];
          var animate = generateRoute(this.props.data[this.props.id], date);
          this.setState({isFetchingAnim: true});
            animate.then(res => {
              this.startAnimation(res);
            }).catch((error) => {
              if (error.response.data.error === 'expired token') {
                var extendedToken = refreshToken(`http://dev.finder-lbs.com:8000/assets/${id.assetId}/history_data?from=${date[0]}&to=${date[1]}&access_token=${window.localStorage.getItem('user')}`);
                extendedToken.then(res => {
                  this.startAnimation(res);
                });
              }
            });
          }else{
            alertMessage('Please, select timeframe first.');
          }
    }

    route = () => {
      var date = [this.props.timer.start, this.props.timer.end];
      if(date[0]!=='START TIME' || date[1]!=='END TIME'){
        var id = this.props.data[this.props.id];

        var route = generateRoute(this.props.data[this.props.id], date);
        this.setState({isFetchingRoute: true});
          route.then(res => {
            this.setState({isFetchingRoute: false});
            var result = this.makeAnimation(res);
            this.props.passRouteData(result);
          }).catch((error) => {
            if (error.response.data.error === 'expired token') {
              var extendedToken = refreshToken(`http://dev.finder-lbs.com:8000/assets/${id.assetId}/history_data?from=${date[0]}&to=${date[1]}&access_token=${window.localStorage.getItem('user')}`);
              extendedToken.then(res => {
                this.setState({isFetchingRoute: false});
                var result = this.makeAnimation(res);
                this.props.passRouteData(result);
              });
            }
          });
        }else{
          alertMessage('Please, select timeframe first.');
        }
    }



    changeDistance(distance){

      let current = {
        info: this.props.data[this.props.id],
        radius: distance
      }

      let response = getData(`http://dev.finder-lbs.com:8000/assets/${current.info.assetId}/nearest_assets?radius=${distance}&access_token=`);
      response.then((res) => {
        this.props.passNearVehicle([res.data, current]);
      })
    }


    toggle = () => {

      // let promise = new Promise((resolve, reject) => {
        this.setState({
          engineStatus: !this.state.engineStatus
        });
      // });
      let toggleVal = this.state.engineStatus?'off':'on';

      let id = this.props.data[this.props.id].assetId;
      // console.log(assstID.assetId);
      let sendRequest = getData(`http://dev.finder-lbs.com:8000/assets/${id}/engine?state=${toggleVal}&access_token=`);
      sendRequest.then((res) => {
         console.log(res.data)
      })
    }

    render(){

        const {name, speed, status, time,nlm, isFetchingAnim, isFetchingRoute, isRunning} = this.state;
        if(this.state.name!=='DEFAULT'){
          return (
              <div style={{textAlign:'left', padding:10}}>
                  <h5 className="ui center aligned icon header">
                  <i className="circular car icon"></i>

                        {name}
                        {this.props.userData!=null?<div>{this.props.userData[0]}</div>:null}
                        {this.props.userData!=null?<div>{this.props.userData[1]}</div>:null}

                  </h5>
                  <div>
                      <p><i className="car icon"></i> Speed: {speed} km/h</p>
                      <p><i className="arrow right icon"></i> Last seen on {time}</p>
                      <p><i className="arrow right icon"></i> Service Status: {status}</p>
                  </div>
                  <br/>
                  <div >
                      <h4><strong><i className="map icon"></i> Nearest Landmarks</strong></h4>
                        {
                          nlm.map( (item, idx) => (
                            <p key={idx}>
                              <i className="marker icon"></i>
                              {item}
                            </p>
                          ))
                        }
                  </div><br/>
                  {/*
                    <i>[If you are not satisfied with the landmarks, then visit Kothay? and you can]</i>
                  <Button size="small" style={{marginBottom:5,borderRadius:0, }} fluid color='teal'>Create Bill for The Period</Button>
                  <Button size="small" style={{marginBottom:5,borderRadius:0}} color="google plus" fluid>Bills</Button>

                  */}
                  <Button.Group fluid>
                    <Button disabled={isRunning} style={{borderRadius:0}} color="google plus" loading={isFetchingRoute} onClick={this.route}>Route</Button>
                    <Button disabled={isRunning} style={{borderRadius:0}} color='teal' loading={isFetchingAnim} onClick={this.animate}>Animate</Button>
                  </Button.Group>
                  {
                    window.localStorage.getItem('rancon')?
                    <div>
                      <h5>Search Asset Within (km)</h5>
                      <Button circular color='teal' onClick={this.changeDistance.bind(this,1)}>1</Button>
                      <Button circular color='teal' onClick={this.changeDistance.bind(this,2)}>2</Button>
                      <Button circular color='teal' onClick={this.changeDistance.bind(this,3)}>3</Button>
                      <Button circular color='teal' onClick={this.changeDistance.bind(this,4)}>4</Button>
                      <Button circular color='teal' onClick={this.changeDistance.bind(this,5)}>5</Button>
                    </div>: null
                  }

                <br/>
                <Checkbox
                  checked = {this.state.engineStatus}
                  toggle
                  onClick={this.toggle}
                  label ="Engine ON/OFF"
                />


              </div>
          );
        }else{
          return null;
        }

    }
}

export default Details;