import "./style/TpSlForm.scss";

import React, {Component} from "react";
import {Provider} from 'sbx-react-core';
import Select from "sbx-react-select";
import InputStep from "components/InputStep";
import Lang from "components/Language";

import {validatePrice} from "helpers/Validate";
import {getOrderSpreadFromStop, getOrderStopFromSpread} from "libs/Assets";
import {orderIsActive, orderIsBuy, getOrderStopFromAmt, getOrderAmtFromStop} from "libs/Orders";

@Provider({
    asset: props => ['assets', props.order.symbol],
    accounts: ['profile', 'accounts'],
    tokens: ['tokens'],
    lang: ['settings','lang']
})

export default class TpSlForm extends Component {
    state = {
        sl: {
            view: "price",
            price: this.props.order.sl ? String(this.props.order.sl) : (orderIsBuy[this.props.order.cmd]?this.props.order.bid:this.props.order.ask),
            pips: '',
            profit: ''
        },
        tp: {
            view: "price",
            price: this.props.order.tp ? String(this.props.order.tp) : (!orderIsBuy[this.props.order.cmd]?this.props.order.bid:this.props.order.ask),
            pips: '',
            profit: '',
        },
        ts: this.props.order.ts || ''
    };

    componentWillReceiveProps(nextProps, nextContext) {
        const {volume, cmd, open_price, slIsEnable, tpIsEnable} = nextProps.order;
        const {sl, tp} = this.state;
        if(slIsEnable) {
            this.updateStops({
                stopType: 'sl',
                valueType: sl.view,
                value: this.state.sl[sl.view],
                volume,
                cmd,
                open_price
            })
        } else if(slIsEnable !== this.props.order.slIsEnable) {
            this.setState({
                sl: {
                    view: "price",
                    pips: '',
                    profit: '',
                    price: this.props.order.sl ? String(this.props.order.sl) : (orderIsBuy[this.props.order.cmd]?this.props.order.bid:this.props.order.ask),
                }
            }, () => {
                this.props.onChange({
                    sl: 0,
                    tp: tp.price.length ? parseFloat(tp.price) : 0
                })
            })
        }
        if(tpIsEnable) {
            this.updateStops({
                stopType: 'tp',
                valueType: tp.view,
                value: this.state.tp[tp.view],
                volume,
                cmd,
                open_price
            })
        } else if(tpIsEnable !== this.props.order.tpIsEnable) {
            this.setState({
                tp: {
                    view: "price",
                    pips: '',
                    profit: '',
                    price: this.props.order.tp ? String(this.props.order.tp) : (!orderIsBuy[this.props.order.cmd]?this.props.order.bid:this.props.order.ask),
                }
            }, () => {
                this.props.onChange({
                    tp: 0,
                    sl: sl.price.length ? parseFloat(sl.price) : 0
                })
            })
        }
    }

    componentWillUnmount() {
        this.props.onChange && this.props.onChange({sl: 0, tp: 0})
    }

    updateStops = ({stopType, valueType, value, volume, cmd, open_price}) => {
        const {slIsEnable, tpIsEnable} = this.props.order;
        const nextValue = this.convert({
            stopType,
            valueType,
            value,
            open_price,
            cmd,
            volume
        });
        this.setState({
            [stopType]: {...this.state[stopType], ...nextValue}
        }, () => {
            this.props.onChange({
                sl: this.state.sl.price.length && slIsEnable ? parseFloat(this.state.sl.price) : 0,
                tp: this.state.tp.price.length && tpIsEnable ? parseFloat(this.state.tp.price) : 0
            })
        })
    };

    convert = ({stopType, valueType, value, open_price, volume, cmd}) => {
        const {asset, order} = this.props;
        const {digits} = asset;
        const {symbol} = order;
        let result = {
            price: "",
            pips: "",
            profit: ""
        };
        if(!String(value).length) {
            return result
        }
        result[valueType] = parseFloat(value);
        switch(valueType) {
            case 'price': {
                result.pips = getOrderSpreadFromStop({
                    stop_type: stopType,
                    stop_price: value,
                    open_price,
                    cmd,
                    digits
                });
                result.profit = getOrderAmtFromStop({
                    symbol,
                    cmd,
                    volume,
                    stopType: stopType,
                    stopValue: result.price,
                    isOpenOrder: orderIsActive(cmd),
                    open_price
                });
                break;
            }
            case 'pips': {
                result.price = getOrderStopFromSpread({
                    stop_type: stopType,
                    stop_spread: value,
                    open_price,
                    cmd,
                    digits
                });
                result.profit = getOrderAmtFromStop({
                    symbol,
                    cmd,
                    volume,
                    stopType: stopType,
                    stopValue: result.price,
                    isOpenOrder: orderIsActive(cmd),
                    open_price
                });
                break;
            }
            case 'profit': {
                result.price = getOrderStopFromAmt({
                    symbol,
                    cmd,
                    volume: volume,
                    stopType: stopType,
                    amt: value,
                    isOpenOrder: orderIsActive(cmd),
                    open_price
                });
                result.pips = getOrderSpreadFromStop({
                    stop_type: stopType,
                    stop_price: result.price,
                    open_price,
                    cmd,
                    digits
                });
                break;
            }
        }
        return {
            price: result.price.toFixed(digits),
            pips: String(result.pips),
            profit: result.profit.toFixed(2)
        }
    };
    render() {
        const {asset, order, accounts, tokens, lang} = this.props;
        const {sl, tp} = this.state;
        const {slIsEnable, tpIsEnable, volume, cmd, open_price} = order;
        const {digits} = asset;
        const {currency} = accounts[0];
        const vol_l = String(volume).length;

        return (
            <div className="tpsl-form">
                {
                    slIsEnable &&
                    <div className="tpsl-form-col col-sl">
                        <div className="tpsl-form-row">
                            <Select
                                value={sl.view}
                                onSelect={value => {
                                    this.setState({
                                        sl: {price: '', pips: '', profit: '', view: value.value}
                                    }, () => {
                                        this.updateStops({
                                            stopType: 'sl',
                                            valueType: value.value,
                                            value: '',
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    })
                                }}
                                noInput={true}
                                options={[
                                    {
                                        value: "pips",
                                        label: tokens[lang]['PIPS']
                                    },
                                    {
                                        value: "profit",
                                        label: tokens[lang]['SL_PROFIT']
                                    },
                                    {
                                        value: "price",
                                        label: tokens[lang]['PRICE']
                                    }
                                ]}
                            />
                            {
                                sl.view === "pips" &&
                                <InputStep
                                    value={sl.pips}
                                    valueMin={1}
                                    valueMax={9999999}
                                    valueStep={1}
                                    validate={validatePrice}
                                    onChange={value => {
                                        this.updateStops({
                                            stopType: 'sl',
                                            valueType: 'pips',
                                            value,
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    }}
                                />
                            }
                            {
                                sl.view === "profit" &&
                                <InputStep
                                    value={sl.profit}
                                    valueMin={0.01}
                                    valueMax={9999999}
                                    valueStep={0.01}
                                    validate={validatePrice}
                                    onChange={value => {
                                        this.updateStops({
                                            stopType: 'sl',
                                            valueType: 'profit',
                                            value,
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    }}
                                />
                            }
                            {
                                sl.view === "price" &&
                                <InputStep
                                    value={sl.price}
                                    valueMin={(0.1 ** digits).toFixed(digits)}
                                    valueMax={9999999}
                                    valueStep={(0.1 ** digits).toFixed(digits)}
                                    validate={validatePrice}
                                    onChange={value => {
                                        this.updateStops({
                                            stopType: 'sl',
                                            valueType: 'price',
                                            value,
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    }}
                                />
                            }
                        </div>
                        <div className="tpsl-form-row">
                            {
                                sl.view !== "price" &&
                                <div><Lang>PRICE</Lang>: {String(sl.price).length && vol_l ? parseFloat(sl.price).toFixed(digits) : 0}</div>
                            }
                            {
                                sl.view !== "profit" &&
                                <div><Lang>SL_PROFIT</Lang>: {parseFloat(String(sl.profit).length && vol_l ? sl.profit : 0).toFixed(2)} {currency}</div>
                            }
                            {
                                sl.view !== "pips" &&
                                <div><Lang>PIPS</Lang>: {String(sl.pips).length && vol_l ? sl.pips : 0}</div>
                            }
                        </div>
                    </div>
                }
                {
                    tpIsEnable &&
                    <div className="tpsl-form-col ml-auto col-tp">
                        <div className="tpsl-form-row">
                            <Select
                                value={tp.view}
                                onSelect={value => {
                                    this.setState({
                                        tp: { pips: '', profit: '', view: value.value}
                                    }, () => {
                                        this.updateStops({
                                            stopType: 'tp',
                                            valueType: value.value,
                                            value: '',
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    })
                                }}
                                noInput={true}
                                options={[
                                    {
                                        value: "pips",
                                        label: tokens[lang]['PIPS']
                                    },
                                    {
                                        value: "profit",
                                        label: tokens[lang]['TP_PROFIT']
                                    },
                                    {
                                        value: "price",
                                        label: tokens[lang]['PRICE']
                                    }
                                ]}
                            />
                            {
                                tp.view === "pips" &&
                                <InputStep
                                    value={tp.pips}
                                    valueMin={1}
                                    valueMax={9999999}
                                    valueStep={1}
                                    validate={validatePrice}
                                    onChange={value => {
                                        this.updateStops({
                                            stopType: 'tp',
                                            valueType: 'pips',
                                            value,
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    }}
                                />
                            }
                            {
                                tp.view === "profit" &&
                                <InputStep
                                    value={tp.profit}
                                    valueMin={0.01}
                                    valueMax={9999999}
                                    valueStep={0.01}
                                    validate={validatePrice}
                                    onChange={value => {
                                        this.updateStops({
                                            stopType: 'tp',
                                            valueType: 'profit',
                                            value,
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    }}
                                />
                            }
                            {
                                tp.view === "price" &&
                                <InputStep
                                    value={tp.price}
                                    valueMin={(0.1 ** digits).toFixed(digits)}
                                    valueMax={9999999}
                                    valueStep={(0.1 ** digits).toFixed(digits)}
                                    validate={validatePrice}
                                    onChange={value => {
                                        this.updateStops({
                                            stopType: 'tp',
                                            valueType: 'price',
                                            value,
                                            volume,
                                            cmd,
                                            open_price
                                        })
                                    }}
                                />
                            }
                        </div>
                        <div className="tpsl-form-row">
                            {
                                tp.view !== "price" &&
                                <div><Lang>PRICE</Lang>: {String(tp.price).length && vol_l ? parseFloat(tp.price).toFixed(digits) : 0}</div>
                            }
                            {
                                tp.view !== "profit" &&
                                <div><Lang>TP_PROFIT</Lang>: {parseFloat(String(tp.profit).length && vol_l ? tp.profit : 0).toFixed(2)} {currency}</div>
                            }
                            {
                                tp.view !== "pips" &&
                                <div><Lang>PIPS</Lang>: {String(tp.pips).length && vol_l ? tp.pips : 0}</div>
                            }
                        </div>
                    </div>
                }
            </div>
        )
    }
}
