<commit_before>import React from "react";
import ZfApi from "react-foundation-apps/src/utils/foundation-api";
import Modal from "react-foundation-apps/src/modal";
import Trigger from "react-foundation-apps/src/trigger";
import Translate from "react-translate-component";
import ChainTypes from "../Utility/ChainTypes";
import BindToChainState from "../Utility/BindToChainState";
import FormattedAsset from "../Utility/FormattedAsset";
import utils from "common/utils";
import classNames from "classnames";
import AmountSelector from "../Utility/AmountSelector";
import BalanceComponent from "../Utility/BalanceComponent";
import WalletApi from "rpc_api/WalletApi";
import WalletDb from "stores/WalletDb";
import FormattedPrice from "../Utility/FormattedPrice";
import counterpart from "counterpart";
import HelpContent from "../Utility/HelpContent";
import Immutable from "immutable";

let wallet_api = new WalletApi();

/**
 *  Given an account and an asset id, render a modal allowing modification of a margin position for that asset
 *
 *  Expected Properties:
 *     quote_asset:  asset id, must be a bitasset
 *     account: full_account object for the account to use
 *
 */

@BindToChainState({keep_updating: true})
class BorrowModalContent extends React.Component {

    static propTypes = {
        quote_asset: ChainTypes.ChainAsset.isRequired,
        bitasset_balance: ChainTypes.ChainObject,
        backing_asset: ChainTypes.ChainAsset.isRequired,
        backing_balance: ChainTypes.ChainObject,
        call_orders: ChainTypes.ChainObjectsList
    }

    constructor() {
        super();
        this.state = {
            short_amount: 0,
            collateral: 0,
            collateral_ratio: 0,
            errors: this._getInitialErrors(),
            isValid: false,
            original_position: {
                debt: 0,
                collateral: 0
            }
        };
    }

    componentDidMount() {
        let currentPosition = this._getCurrentPosition();
        let debt = utils.get_asset_amount(currentPosition.debt, this.props.quote_asset);
        let collateral = utils.get_asset_amount(currentPosition.collateral, this.props.backing_asset);

        if (currentPosition.collateral) {
            let newState = {
                short_amount: debt ? debt.toString() : null,
                collateral: collateral ? collateral.toString() : null,
                collateral_ratio: this._getCollateralRatio(debt, collateral),
                original_position: {
                    debt: debt,
                    collateral: collateral
                }
            };

            this.setState(newState);
            this._setUpdatedPosition(newState);
        }
    }


    shouldComponentUpdate(nextProps, nextState) {
        // console.log("nextProps:", nextProps);
        // console.log("state not equal:", !utils.are_equal_shallow(nextState, this.state));
        // console.log("props equal:", utils.are_equal_shallow(nextProps, this.props));
        // console.log("bitasset not equal:", !Immutable.is(nextProps.quote_asset.get("bitasset"), this.props.quote_asset.get("bitasset")))
        // console.log("backing asset not equal:", !nextProps.backing_asset.get("symbol") === this.props.backing_asset.get("symbol"))
        return (
            !utils.are_equal_shallow(nextState, this.state) ||
            !Immutable.is(nextProps.quote_asset.get("bitasset"), this.props.quote_asset.get("bitasset")) ||
            !nextProps.backing_asset.get("symbol") === this.props.backing_asset.get("symbol")
        );
    }

    _getInitialErrors() {
        return {
            collateral_balance: null,
            ratio_too_high: null
        };
    }

    confirmClicked(e) {
        e.preventDefault();
        ZfApi.publish(this.props.modalId, "close");       
    }

    _onBorrowChange(e) {
        let feed_price = this._getFeedPrice();
        let amount = e.amount.replace( /,/g, "" );
        let newState = {
            short_amount: amount,
            collateral: (this.state.collateral_ratio * (amount / feed_price)).toFixed(this.props.backing_asset.get("precision")),
            collateral_ratio: this.state.collateral_ratio
        }

        this.setState(newState);
        this._validateFields(newState);
        this._setUpdatedPosition(newState);
    }
    
    _onCollateralChange(e) {
        let amount = e.amount.replace( /,/g, "" );

        let feed_price = this._getFeedPrice();

        let newState = {
            short_amount: this.state.short_amount,
            collateral: amount,
            collateral_ratio: amount / (this.state.short_amount / feed_price)
        }

        this.setState(newState);
        this._validateFields(newState);
        this._setUpdatedPosition(newState);
    }

    _onRatioChange(e) {
        let feed_price = this._getFeedPrice();

        let ratio = e.target.value;

        let newState = {
            short_amount: this.state.short_amount,
            collateral: ((this.state.short_amount / feed_price) * ratio).toFixed(this.props.backing_asset.get("precision")),
            collateral_ratio: ratio
        }

        this.setState(newState);
        this._validateFields(newState);
        this._setUpdatedPosition(newState);
    }

    _setUpdatedPosition(newState) {
        this.setState({
            newPosition: (parseFloat(newState.short_amount) / parseFloat(newState.collateral))
        });
    }


    _validateFields(newState) {
        let errors = this._getInitialErrors();
        let {original_position} = this.state;
        let backing_balance = !this.props.backing_balance ? {balance: 0} : this.props.backing_balance.toJS();


        if ( (parseFloat(newState.collateral)-original_position.collateral) > utils.get_asset_amount(backing_balance.balance, this.props.backing_asset.toJS())) {
            errors.collateral_balance = counterpart.translate("borrow.errors.collateral");
        }
        debugger;
        let isValid = (newState.short_amount >= 0 && newState.collateral >= 0) && (newState.short_amount != original_position.debt || newState.collateral != original_position.collateral);

        let sqp = this.props.quote_asset.getIn(["bitasset", "current_feed", "maximum_short_squeeze_ratio"]) / 1000;
        let mcr = this.props.quote_asset.getIn(["bitasset", "current_feed", "maintenance_collateral_ratio"]) / 1000
        if (parseFloat(newState.collateral_ratio) < (sqp * mcr)) {
            errors.below_maintenance = counterpart.translate("borrow.errors.below");
            isValid = false;
        }

        this.setState({errors, isValid});
    }

    _onSubmit(e) {
        e.preventDefault();
        
        let quotePrecision = utils.get_asset_precision(this.props.quote_asset.get("precision"));
        let backingPrecision = utils.get_asset_precision(this.props.backing_asset.get("precision"));
        let currentPosition = this._getCurrentPosition();

        var tr = wallet_api.new_transaction();
        // console.log("tr object:", {
        //     "fee": {
        //         amount: 0,
        //         asset_id: 0
        //     },
        //     "funding_account": this.props.account.get("id"),
        //     "delta_collateral": {
        //         "amount": parseInt(this.state.collateral * backingPrecision - currentPosition.collateral, 10),
        //         "asset_id": this.props.backing_asset.get("id")
        //     },
        //     "delta_debt": {<commit_msg>Remove debugger from BorrowModal<commit_after>import React from "react";
import ZfApi from "react-foundation-apps/src/utils/foundation-api";
import Modal from "react-foundation-apps/src/modal";
import Trigger from "react-foundation-apps/src/trigger";
import Translate from "react-translate-component";
import ChainTypes from "../Utility/ChainTypes";
import BindToChainState from "../Utility/BindToChainState";
import FormattedAsset from "../Utility/FormattedAsset";
import utils from "common/utils";
import classNames from "classnames";
import AmountSelector from "../Utility/AmountSelector";
import BalanceComponent from "../Utility/BalanceComponent";
import WalletApi from "rpc_api/WalletApi";
import WalletDb from "stores/WalletDb";
import FormattedPrice from "../Utility/FormattedPrice";
import counterpart from "counterpart";
import HelpContent from "../Utility/HelpContent";
import Immutable from "immutable";

let wallet_api = new WalletApi();

/**
 *  Given an account and an asset id, render a modal allowing modification of a margin position for that asset
 *
 *  Expected Properties:
 *     quote_asset:  asset id, must be a bitasset
 *     account: full_account object for the account to use
 *
 */

@BindToChainState({keep_updating: true})
class BorrowModalContent extends React.Component {

    static propTypes = {
        quote_asset: ChainTypes.ChainAsset.isRequired,
        bitasset_balance: ChainTypes.ChainObject,
        backing_asset: ChainTypes.ChainAsset.isRequired,
        backing_balance: ChainTypes.ChainObject,
        call_orders: ChainTypes.ChainObjectsList
    }

    constructor() {
        super();
        this.state = {
            short_amount: 0,
            collateral: 0,
            collateral_ratio: 0,
            errors: this._getInitialErrors(),
            isValid: false,
            original_position: {
                debt: 0,
                collateral: 0
            }
        };
    }

    componentDidMount() {
        let currentPosition = this._getCurrentPosition();
        let debt = utils.get_asset_amount(currentPosition.debt, this.props.quote_asset);
        let collateral = utils.get_asset_amount(currentPosition.collateral, this.props.backing_asset);

        if (currentPosition.collateral) {
            let newState = {
                short_amount: debt ? debt.toString() : null,
                collateral: collateral ? collateral.toString() : null,
                collateral_ratio: this._getCollateralRatio(debt, collateral),
                original_position: {
                    debt: debt,
                    collateral: collateral
                }
            };

            this.setState(newState);
            this._setUpdatedPosition(newState);
        }
    }


    shouldComponentUpdate(nextProps, nextState) {
        // console.log("nextProps:", nextProps);
        // console.log("state not equal:", !utils.are_equal_shallow(nextState, this.state));
        // console.log("props equal:", utils.are_equal_shallow(nextProps, this.props));
        // console.log("bitasset not equal:", !Immutable.is(nextProps.quote_asset.get("bitasset"), this.props.quote_asset.get("bitasset")))
        // console.log("backing asset not equal:", !nextProps.backing_asset.get("symbol") === this.props.backing_asset.get("symbol"))
        return (
            !utils.are_equal_shallow(nextState, this.state) ||
            !Immutable.is(nextProps.quote_asset.get("bitasset"), this.props.quote_asset.get("bitasset")) ||
            !nextProps.backing_asset.get("symbol") === this.props.backing_asset.get("symbol")
        );
    }

    _getInitialErrors() {
        return {
            collateral_balance: null,
            ratio_too_high: null
        };
    }

    confirmClicked(e) {
        e.preventDefault();
        ZfApi.publish(this.props.modalId, "close");       
    }

    _onBorrowChange(e) {
        let feed_price = this._getFeedPrice();
        let amount = e.amount.replace( /,/g, "" );
        let newState = {
            short_amount: amount,
            collateral: (this.state.collateral_ratio * (amount / feed_price)).toFixed(this.props.backing_asset.get("precision")),
            collateral_ratio: this.state.collateral_ratio
        }

        this.setState(newState);
        this._validateFields(newState);
        this._setUpdatedPosition(newState);
    }
    
    _onCollateralChange(e) {
        let amount = e.amount.replace( /,/g, "" );

        let feed_price = this._getFeedPrice();

        let newState = {
            short_amount: this.state.short_amount,
            collateral: amount,
            collateral_ratio: amount / (this.state.short_amount / feed_price)
        }

        this.setState(newState);
        this._validateFields(newState);
        this._setUpdatedPosition(newState);
    }

    _onRatioChange(e) {
        let feed_price = this._getFeedPrice();

        let ratio = e.target.value;

        let newState = {
            short_amount: this.state.short_amount,
            collateral: ((this.state.short_amount / feed_price) * ratio).toFixed(this.props.backing_asset.get("precision")),
            collateral_ratio: ratio
        }

        this.setState(newState);
        this._validateFields(newState);
        this._setUpdatedPosition(newState);
    }

    _setUpdatedPosition(newState) {
        this.setState({
            newPosition: (parseFloat(newState.short_amount) / parseFloat(newState.collateral))
        });
    }


    _validateFields(newState) {
        let errors = this._getInitialErrors();
        let {original_position} = this.state;
        let backing_balance = !this.props.backing_balance ? {balance: 0} : this.props.backing_balance.toJS();


        if ( (parseFloat(newState.collateral)-original_position.collateral) > utils.get_asset_amount(backing_balance.balance, this.props.backing_asset.toJS())) {
            errors.collateral_balance = counterpart.translate("borrow.errors.collateral");
        }
        let isValid = (newState.short_amount >= 0 && newState.collateral >= 0) && (newState.short_amount != original_position.debt || newState.collateral != original_position.collateral);

        let sqp = this.props.quote_asset.getIn(["bitasset", "current_feed", "maximum_short_squeeze_ratio"]) / 1000;
        let mcr = this.props.quote_asset.getIn(["bitasset", "current_feed", "maintenance_collateral_ratio"]) / 1000
        if (parseFloat(newState.collateral_ratio) < (sqp * mcr)) {
            errors.below_maintenance = counterpart.translate("borrow.errors.below");
            isValid = false;
        }

        this.setState({errors, isValid});
    }

    _onSubmit(e) {
        e.preventDefault();
        
        let quotePrecision = utils.get_asset_precision(this.props.quote_asset.get("precision"));
        let backingPrecision = utils.get_asset_precision(this.props.backing_asset.get("precision"));
        let currentPosition = this._getCurrentPosition();

        var tr = wallet_api.new_transaction();
        // console.log("tr object:", {
        //     "fee": {
        //         amount: 0,
        //         asset_id: 0
        //     },
        //     "funding_account": this.props.account.get("id"),
        //     "delta_collateral": {
        //         "amount": parseInt(this.state.collateral * backingPrecision - currentPosition.collateral, 10),
        //         "asset_id": this.props.backing_asset.get("id")
        //     },
        //     "delta_debt": {
{'fraction_non_alphanumeric': 0.11845545350941879, 'fraction_numerical': 0.0026815043239257225, 'mean_word_length': 2.576600335650923, 'pattern_counts': {'":': 12, '<': 5, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1873675', 'n_tokens_mistral': 4284, 'n_tokens_neox': 4181, 'n_words': 750}