import React, {Component} from "react"
import {Container, Table} from "react-bootstrap"
import {NewTickData, PositionState, socket} from '../';


export class PositionTable extends Component<{}, { positions: Array<PositionState> }> {
    state = {
        positions: []
    }

    constructor(props) {
        super(props)
    }

    componentDidMount() {
        socket.on('new_tick', (data: NewTickData) => {
            this.setState({
                positions: data.positions
            })
        })
    }

    tableData() {
        return this.state.positions.map((position: PositionState, idx) => {
            return (<tr key={position.id}>
                <th>{position.id}</th>
                <th>{position.symbol}</th>
                <th>{position.profit_loss.toFixed(2)}</th>
                <th>{position.profit_loss_percentage.toFixed(2)} %</th>
            </tr>)
        })
    }

    render() {
        return (
            <Container className="d-flex flex-column mt-2">
                <div className="border-bottom">
                    <h2>Open positions</h2>
                </div>
                <Table id="positions" size="sm" hover striped bordered className="mt-2 text-center">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <th>Symbol</th>
                        <th>P/L</th>
                        <th>P/L %</th>
                    </tr>
                    </thead>
                    <tbody>
                    {this.tableData()}
                    </tbody>
                </Table>
            </Container>
        )
    }
}