import React from 'react'
import PropTypes from 'prop-types'
import {Redirect} from 'react-router-dom'
import PageNotFound from 'containers/pages/not-found'
import routes from 'global/constants/routes'

class SearchResolver extends React.Component {
    securityId = null

    constructor(props) {
        super(props)

        const searchQuery = props.location.search
        const searchParams = new URLSearchParams(searchQuery)
        this.securityId = searchParams.get('securityId')
    }

    get isStockSearch() {
        return true
    }

    get resolvedPath() {
        if (!this.securityId) {
            return null
        }

        if (this.isStockSearch) {
            return `${routes.STOCK_PROFILE}/${encodeURIComponent(
                this.securityId
            )}`
        }

        // We currently only have stock search so we should not encounter
        // this case.
        return null
    }

    render() {
        if (!this.resolvedPath) {
            return <PageNotFound />
        }

        const {
            location: {search, hash},
        } = this.props
        return <Redirect to={{pathname: this.resolvedPath, search, hash}} />
    }
}

SearchResolver.propTypes = {
    location: PropTypes.shape({
        search: PropTypes.string,
        hash: PropTypes.string,
    }),
}

export default SearchResolver
