import React from 'react'
import PropTypes from 'prop-types'
import {Redirect} from 'react-router-dom'
import PageNotFound from 'containers/pages/not-found'
import TradeStocksPage from 'containers/pages/trade-stocks'
import TradeEtfsPage from 'containers/pages/trade-etfs'
import TradeCorpBondsPage from 'containers/pages/trade-bonds/templates/corp-bonds'
import TradeGovBondsPage from 'containers/pages/trade-bonds/templates/gov-bonds'
import TradeOptionsPage from 'containers/pages/trade-options'
import routes from 'global/constants/routes'

class TradeSecurity extends React.PureComponent {
    static securityTypeURIs = {
        STOCKS: 'stocks',
        ETFS: 'etfs',
        CORP_BONDS: 'corp-bonds',
        GOV_BONDS: 'gov-bonds',
        OPTIONS: 'options',
        FUTURES: 'futures',
    }

    static templates = {
        [TradeSecurity.securityTypeURIs.STOCKS]: TradeStocksPage,
        [TradeSecurity.securityTypeURIs.ETFS]: TradeEtfsPage,
        [TradeSecurity.securityTypeURIs.CORP_BONDS]: TradeCorpBondsPage,
        [TradeSecurity.securityTypeURIs.GOV_BONDS]: TradeGovBondsPage,
        [TradeSecurity.securityTypeURIs.OPTIONS]: TradeOptionsPage,
    }

    get securityType() {
        const {match} = this.props

        if (!match || !match.params || !match.params.securityType) {
            return null
        }

        return decodeURIComponent(match.params.securityType).toLowerCase()
    }

    render() {
        // If there is no security type provided in the URL, redirect to a
        // default discover page.
        if (!this.securityType) {
            const defaultURL = `${routes.TRADE}${routes.TRADE_STOCKS}`
            return <Redirect to={defaultURL} />
        }

        const TradeSecurityPageTemplate =
            TradeSecurity.templates[this.securityType]

        // If the security type provided in the URL is not one of the currently
        // supported ones, render a PageNotFound.
        if (!TradeSecurityPageTemplate) {
            return <PageNotFound />
        }

        return <TradeSecurityPageTemplate />
    }
}

TradeSecurity.propTypes = {
    match: PropTypes.shape({
        params: PropTypes.shape({
            securityType: PropTypes.string,
        }),
    }),
}

export default TradeSecurity
