import React from "react"
import { Component } from "react"
import Plot from "react-plotly.js"

import { NewTickData, socket } from '../';


type FirstConnectData = {
    ticks: Array<number>,
    prices: Array<number>
}

type PlotState = {
    x: Array<number>,
    y: Array<number>
}

class RPlot extends Component<{}, PlotState> {
    constructor(props) {
        super(props)
    }

    state = {
        x: [],
        y: []
    }

    componentDidMount() {
        socket.on("first_connect", (data: FirstConnectData) => {
            this.setState({
                x: data.ticks,
                y: data.prices
            })
        })

        socket.on("new_tick", (data: NewTickData) => {
            var new_x = [...this.state.x, data.tick]
            var new_y = [...this.state.y, data.price]

            // cutting to up to 500 entries (last 500)
            var x = new_x.slice(Math.max(new_x.length - 500, 0))
            var y = new_y.slice(Math.max(new_y.length - 500, 0))

            this.setState({
                x: x,
                y: y,
            })
        })
    }

    render() {
        return (
            <Plot
                data={[
                    {
                        x: this.state.x,
                        y: this.state.y,
                        type: 'scatter',
                        mode: 'lines+markers',
                        "marker.colorbar": { tickformat: ".1f"}
                    },
                ]}
                layout={{ dragmode: "pan", autosize: true }}
                config={{
                    scrollZoom: true,
                    displayModeBar: false,
                    responsive: true,
                }}
                style={{ width: '100%', height: '90%' }}
            />
        )
    }
}

export default RPlot;
