Skip to content
Snippets Groups Projects
MultipleDayGraph.js 21.9 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
import React, { Component } from "react";
import Chart from "react-apexcharts";
import Form from "react-bootstrap/Form";
import Table from "react-bootstrap/Table"
import Button from "react-bootstrap/Button";
import ButtonGroup from "react-bootstrap/ButtonGroup";
import LAMpoints from "./LAMpoints";

var year = "";
var interval;
var VehicleNumberDataObjectForMultipleDay={};
var AvgSpeedDataObjectForMultipleDay={};

export class MultipleDayGraph extends Component {
  constructor(props) {
    super(props);

    this.state = {
      options: {},
      series: [],

      options2: {},
      series2: [],

      info:{},
      year: "",
      month:"",
      day:"",
      areaID: "",
      lamID: "",
      startDayNumber: "",
      endDayNumber: "",
      vehicleClass: '8',//8 means all classes
      trafficDirection : 'both',

      counter : 0,
      childReady : false,
      error: "",
      message:"",
      toggleDisabled:true,
      btnDisabled : false,
      toggleHide : true,
      
    };
    this.yearHandler = this.yearHandler.bind(this);
    this.startDayNumberHandler = this.startDayNumberHandler.bind(this);
    this.vehicleClassHandler = this.vehicleClassHandler.bind(this);
    this.trafficDirectionHandler = this.trafficDirectionHandler.bind(this);
  }


    async getDataAsStream() {  
        console.log("sending req!")

        var year_ = this.state.year;
        var areaID = this.state.areaID;
        var lamID = this.state.lamID;
        var startDayNumber_ = this.state.startDayNumber;
        var endDayNumber_ = this.state.endDayNumber;
        
        interval = endDayNumber_ - startDayNumber_
        var counter= 0;
        //console.log({interval})
        var url = `http://localhost:3030/api/vehicle/?year=${year_}&areaID=${areaID}&lamID=${lamID}&startDayNumber=${startDayNumber_}&endDayNumber=${endDayNumber_}`;//&vehicleClass=${vehicleClass}
        //var url = `http://localhost:3030/api/vehicle/?year=2019&areaID=01&lamID=101&startDayNumber=5&endDayNumber=30`;//&vehicleClass=${vehicleClass}

        try {
            // Step 1: start the fetch and obtain a reader
            let response = await fetch(url);

            const reader = response.body.getReader();

            // Step 2: get total length
            //const contentLength = +response.headers.get('Content-Length');

            // Step 3: read the data
            var resultList = [];
            //let receivedLength = 0; // received that many bytes at the moment
            //let chunks = []; // array of received binary chunks (comprises the body)
            while(true) {
            
                const {done, value} = await reader.read();

                if (done) {
                    break;
                }
                
                //chunks.push(value);
                //receivedLength += value.length;

                //console.log(`Received ${receivedLength} of ${contentLength}`)

                let result_ = new TextDecoder("utf-8").decode(value);
                let result = JSON.parse(result_)
                resultList.push(resultList);

                console.log(result)

                //getting the vehicle number in each our based on vehicle class from response of the request  
                var vehicle_number = result.vehicle_number;
                
                //filling the missing values of vehicle number to zero
                let final_Vehicle_number = this.fillMissingValues(vehicle_number);
                let vehicleNumber  = this.filterData(final_Vehicle_number);
                
                //getting the cars average speed  based on car category
                var avg_speed = result.avg_speed_km_h;
                //filling the missing values of average speed to zero
                let final_avg_speed = this.fillMissingValues(avg_speed);
                //filtering the data and making it as a nested object
                let avgSpeed_ = this.filterData(final_avg_speed);
                //using the calculateAvgSpeed function it will claculate the avarage speed for each vehicle class
                let avgSpeed = this.calculateAvgSpeed(avgSpeed_) 

                let date = (Object.keys(avgSpeed))[0]

                //saving all days in one object
                VehicleNumberDataObjectForMultipleDay[date]= vehicleNumber[date]
                AvgSpeedDataObjectForMultipleDay[date]= avgSpeed[date]

                //using setDataForGraph function to set the filtered and sorted data as graph's data set
                this.setDataForGraph(VehicleNumberDataObjectForMultipleDay,AvgSpeedDataObjectForMultipleDay);
                counter++;
                this.setState({counter})
                //console.log({vehicleNumber,avgSpeed});
            }

            console.log("all days; ",VehicleNumberDataObjectForMultipleDay)
            this.setState({toggleDisabled: false,btnDisabled:false, toggleHide : false, message : ""});
        }
        catch(er){
            this.setState({btnDisabled:false, message :"" });
            console.log(er);
            let errormsg="";
            
            //errormsg = "No data found for the selected date! Error code ";
            
            errormsg = "Oops something went wrong! Error code ";

            this.setState({error: errormsg})
        }
        
    }  


    calculateAvgSpeed(input){
        //getting the avarage speed of all cars in each hour and saving them i class '8'
        Object.keys(input).forEach(hour =>{
            let direction1 = [];
            let direction2 = [];
            let Vclasses = input[hour];
            Object.keys(Vclasses).forEach(vclass=>{
                            
                if(vclass==='8'){
                    const arrSum = arr => arr.reduce((a,b) => a + b, 0);
                    input[hour]['8']['1'] = ((arrSum(direction1))/direction1.length);
                    input[hour]['8']['2'] = ((arrSum(direction2))/direction2.length);
                    
                    let both = direction1.concat(direction2)
                    input[hour]['8']['both'] = Math.round(((arrSum(both))/both.length) * 10) / 10;
                }else{
                    if(input[hour][vclass]['1'] !==0){
                        
                        direction1.push(input[hour][vclass]['1'])
                    }
                    if(input[hour][vclass]['2'] !==0){
                        
                        direction2.push(input[hour][vclass]['2'])
                    }
                    let avg = 
                    (input[hour][vclass]['1']+
                    input[hour][vclass]['2'])/2;

                    input[hour][vclass]['both'] = Math.round(avg * 10) / 10
                }
            });
        });
        return input;
    }


    setDataForGraph = (Vnumber,Vspeed)=>{

    var VCLASS = this.state.vehicleClass;
    var dates=[];
    var numberData = [];
    var speedData =  [];
    //data for graph
    var trafficDirection = this.state.trafficDirection;

    Object.keys(Vnumber).forEach(key=>{
        dates.push(key);
        numberData.push(Vnumber[key][VCLASS][trafficDirection]);
    });
    Object.keys(Vspeed).forEach(key=>{
        speedData.push(Vspeed[key][VCLASS][trafficDirection]);
    });

    //Setting the fetched data as graph's input data
    this.setState({
            //Data for vehcile number graph
            options:{
                chart: {
                    id: "basic-bar"
                },
                dataLabels: {
                    enabled: false
                },
                xaxis: {
                    categories: dates,
                    title:{
                        text : "Date"
                    }
                },
                yaxis: {
                title: {
                    text: 'Vehicle Number'
                }   
                },
                

                title: {
                text: 'Number of vehicles in each day',
                align: 'center'
                },
                legend: {
                position: 'top',
                horizontalAlign: 'right',
                floating: true,
                offsetY: -25,
                offsetX: -5
                }
                
            },
            series:[{
                name: "Vehicle Number",
                data: numberData
            }],
            //data for avarage speed garaph
            options2:{
                chart: {
                    id: "basic-bar"
                },
                dataLabels: {
                enabled: false
                },
                xaxis: {
                    categories: dates,
                    title:{
                    text : "Date"
                    }
                },
                yaxis: {
                    title: {
                        text: 'Avrage speed km/h'
                    },
                    labels: {
                        formatter: function (value) {
                            return Math.round(value * 10)/10;
                        }
                    }
                
                },
                colors: ['#cc3b31'],

                title: {
                text: 'Avrage Speed in each day',
                align: 'center'
                },
                legend: {
                position: 'top',
                horizontalAlign: 'right',
                floating: true,
                offsetY: -25,
                offsetX: -5
                }
            },
            series2:[{
                name: "Avarage Speed km/h",
                data: speedData
            }],
            
        });
    }

    filterData= (input)=>{
    var DataObj = {};
    let d = {};
    let c = {};

    let sum =0;
    Object.keys(input).forEach((key)=>{
        let value = input[key];
        let keyToList = key.toString().split('_');
        
        let dates = keyToList[0];
        let category =  parseFloat(keyToList[1]);
        let direction = parseFloat(keyToList[2]); 

        c[direction] = Math.round(value * 10) / 10;

        sum = c['1']+c['2'];
        c['both'] = sum;
        d[category] = {...c};
        
        //checking if all the classes 1-7 exists, and then creates class 8 which is total of all classes
        if(d['1'] && d['2'] && d['3'] && d['4'] && d['5'] && d['6'] && d['7']){
        d['8'] = {1:0, 2:0, both:0};
        d['8']['1'] = d['1']['1'] + d['2']['1']+d['3']['1']+d['4']['1']+d['5']['1']+d['6']['1']+d['7']['1'];
        d['8']['2'] = d['1']['2'] + d['2']['2']+d['3']['2']+d['4']['2']+d['5']['2']+d['6']['2']+d['7']['2'];
        d['8']['both'] = d['8']['1'] + d['8']['2'];

        }
        DataObj[dates] = {...d};
        //if()
        
    });
    return DataObj;           
    }

    //function for filling the missing values like vehicle category and its number
    fillMissingValues=(input)=>{
        let firstkey = Object.keys(input)
        let year = firstkey[0].split('_')[0]

        let final = {};
        for (let i = 0; i <= 14; i++) {
        for (let j = 1; j <= 7; j++) {
            for(let x=1; x<=2;x++){
                const key = [`${year}_${j}_${x}`];
                final[key] = input[key];
                if (input[key] === undefined) {
                final[key] = 0;
                }
            }
            
        }
        }
        return final;
    }


    dateTodaynumber = (year, month,day) => {
        var x = new Date(year, 0, 0);
        x = x.getTime();

    
        var d = new Date(year, month, day);
        d = d.getTime();
        var sec = d - x;
        var secToDay = sec / 1000 / 60 / 60 / 24;
        secToDay = Math.floor(secToDay);
        return secToDay;
    }

    yearHandler(e) {
        year = e;
        this.setState({ year });
    }

    monthHandler=(e)=>{
        this.setState({month : e});
    }

    startDayNumberHandler(e) {
        this.setState({day: e});
    }
    endDaynumberHandler = (e)=>{
        console.log(e)
        this.setState({endDayNumber:e})
    }
    
    vehicleClassHandler(e) {
        var vehicleClass = e.target.value;
        this.setState({ vehicleClass },()=>{
            //one day data
            //using setDataForGraph function to set the filtered and sorted data as graph's data set
            this.setDataForGraph(VehicleNumberDataObjectForMultipleDay,AvgSpeedDataObjectForMultipleDay);
        
        });
    }

    trafficDirectionHandler(e){
        var btnID = e.target.id;
        
        let trafficDirection;
        if(btnID ==="direction1"){
            //console.log(btnID)
        trafficDirection=1;
        }else if(btnID ==="direction2"){
            //console.log(btnID)
        trafficDirection=2;
        }else if(btnID === "bothDirection"){
            //console.log(btnID)
            trafficDirection='both';
        } 
        this.setState({trafficDirection},()=>{
            //one day data
            //using setDataForGraph function to set the filtered and sorted data as graph's data set
            this.setDataForGraph(VehicleNumberDataObjectForMultipleDay,AvgSpeedDataObjectForMultipleDay);
        });
    }

    infoHandler = (info)=>{
        var lamID = info.id;
        this.setState({ lamID,info});
    }
    areaHandler = (id)=>{
        var areaID = id;
        this.setState({ areaID});
    }

    isChildreadyHandler = (e)=>{
        this.setState({
        childReady : e
        })
    }
    

    buttonHandler = () => {
        let selectedYear = this.state.year;
        let selectedMonth = this.state.month;
        let selectedDay = this.state.day;
        let selectedEndDay = this.state.endDayNumber;

        let dayNumber = this.dateTodaynumber(selectedYear,selectedMonth,selectedDay);
        let endDayNumber = this.dateTodaynumber(selectedYear,selectedMonth,selectedEndDay)
        
        var inputs = [
        this.state.year,
        this.state.areaID,
        this.state.lamID,
        this.state.month,
        this.state.day,
        this.state.endDayNumber,
        this.state.childReady
        
        ];
        if (
        (inputs[0] === "") |
        (inputs[1] === "") |
        (inputs[2] === "") |
        (inputs[3] === "") |
        (inputs[4] === "") | 
        (inputs[5] === "") | 
        (inputs[6] === false)
        ) {

            this.setState({error:
                "Please make sure that you have chosen right value for dates, Area and LAM point ID fields!",
            });

        } 
        else if( dayNumber === endDayNumber | dayNumber > endDayNumber){
            this.setState({error:
                "End day can not be equal or smaller then the start day!",
            });
        }
        
        else {
            this.setState({
                error : "",
                message : "Please wait while the data is beeing processed!",
                btnDisabled : true
            })
            this.setState({startDayNumber:dayNumber,endDayNumber},()=>{
                this.getDataAsStream();
                console.log("Sending request to server!")
            });
            
        //console.log(this.state)
        }
    }

    

    render() {
        let id,name, coordinates,status,address,municipality,province,direction1,direction2,startTime='';
        if (this.state.info['id'] !== undefined){
        id = this.state.info.id;
        status = this.state.info.status;
        name = this.state.info.name;
        coordinates = this.state.info.coordinatesETRS89.toString();
        address = this.state.info.address.en;
        municipality = this.state.info.municipality;
        province = this.state.info.province;
        startTime = this.state.info.startTime;
        direction1 = this.state.info.direction1;
        direction2 = this.state.info.direction2;
        }
        

        return (

        <div className="oneDayGraphComponent">

        <div className="grid-container">
            <div className="grid-item-heading">
                Data analysis for multiple day
            </div>

            <div className="grid-item-form">
                <div style={{fontSize : 16, color : '#eb4034'}}>{this.state.error}</div>

                <LAMpoints 
                    info={this.infoHandler} 
                    SelectedAreaID = {this.areaHandler} 
                    selectedYear={this.yearHandler} 
                    selectedMonth={this.monthHandler} 
                    selectedDay={this.startDayNumberHandler} 
                    selectedEndDay= {this.endDaynumberHandler}
                    ready = {this.isChildreadyHandler} 
                    endDayDisabled = {false}
            
                />

                <Button
                type="button"
                className="my-1 mr-sm-2"
                id="drawGraph"
                onClick={this.buttonHandler}
                disabled={this.state.btnDisabled}
                block
                >
                {this.state.btnDisabled ? 'Loading ...' : 'Draw Graph'}
                </Button>

            
                <div style={{fontSize : 16, color : '#1878b5'}}>
                    {this.state.message}

                    <div hidden={!this.state.btnDisabled}>
                    
                         Loading {this.state.counter} of {interval+1} 

                    </div>
                    
                </div>
                

                <div className="grid-item-info">
                <h5>TMS Information:</h5>
                <Table striped size="sm" style={{fontSize:'16px', color:"#0077c7"}}>
                    
                    <tbody>
                    <tr>
                        <td> TMS ID: </td>
                        <td>{id}</td>
                        
                    </tr>
                    <tr>
                        <td>Name: </td>
                        <td>{name}</td>
                        
                    </tr>
                    <tr>
                        <td>Status: </td>
                        <td>{status}</td>
                    
                    </tr>

                    <tr>
                        <td> Coordinates: </td>
                        <td>{coordinates}</td>
                    </tr>

                    <tr>
                        <td>Address: </td>
                        <td>{address}</td>
                    </tr>

                    <tr>
                        <td>Municipality: </td>
                        <td>{municipality}</td>
                    </tr>
                    <tr>
                        <td>Province: </td>
                        <td>{province}</td>
                    </tr>
                    <tr>
                        <td>Start Time: </td>
                        <td>{startTime}</td>
                    </tr>
                    <tr>
                        <td>Direction 1: </td>
                        <td>{direction1}</td>
                    </tr>
                    <tr>
                        <td>Direction 2: </td>
                        <td>{direction2}</td>
                    </tr>
                    </tbody>
                </Table>
                </div>
                
            </div>

            <div className="grid-item-filter">
            
            
            <Form style= {{width : "100%"}}> 
                <Form.Label
                className="my-1 mr-2"
                htmlFor="inlineFormCustomSelectPref"
                >
                <h5>Filters:</h5>
                </Form.Label><br></br>


                <Form.Label
                className="my-1 mr-2"
                htmlFor="inlineFormCustomSelectPref"
                >
                vehicle Category
                </Form.Label>
                <Form.Control
                as="select"
                className="my-1 mr-sm-2"
                id="vehicleClass"
                custom
                onChange={this.vehicleClassHandler} 
                disabled={this.state.toggleDisabled}
                >
                <option value="8">All</option>
                <option value="1">1 HA-PA (henkilö- tai pakettiauto)</option>
                <option value="2">2 KAIP (kuorma-auto ilman perävaunua)</option>
                <option value="3">3 Linja-autot</option>
                <option value="4">4 KAPP (kuorma-auto ja puoliperävaunu)</option>
                <option value="5">5 KATP (kuorma-auto ja täysperävaunu)</option>
                <option value="6">6 HA + PK (henkilöauto ja peräkärry)</option>
                <option value="7">7 HA + AV (henkilöauto ja asuntovaunu)</option>
                </Form.Control>

                <ButtonGroup size="sm" className="mb-2 " style={{width :"100%"}} hidden={this.state.toggleHide}>
                    <Button 
                        type="button"
                        className="my-4"
                        id="direction1"
                        onClick={this.trafficDirectionHandler}
                    >Direction 1</Button>

                    <Button 
                        type="button"
                        className="my-4"
                        id="direction2"
                        onClick={this.trafficDirectionHandler}
                    >Direction 2</Button>

                    <Button 
                        style={{minWidth : 120 }}
                        type="button"
                        className="my-4"
                        id="bothDirection"
                        onClick={this.trafficDirectionHandler}
                    >Both Direction</Button>
                </ButtonGroup>
            </Form>
            </div>

            <div className="grid-item-graph1">
                <div className="grid-item-graph-child"> 
                <Chart
                options={this.state.options}
                series={this.state.series}
                type="bar"
                width="500"
                />
                </div>
            
            </div>
            
            <div className="grid-item-graph2">
                <div className="grid-item-graph-child"> 
                <Chart
                options={this.state.options2}
                series={this.state.series2}
                type="bar"
                width="500"
                />
                </div>
            </div>  
        </div>
        
        </div>
        );
    }
}

export default MultipleDayGraph;