// timeline.tsx
// Copyright (C) 2020  Dwayne Harris

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

import React, { FC, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'

import { handleApiError } from '../api/errors'
import { fetchTimeline } from '../actions/posts'
import { getTimeline } from '../selectors/posts'
import { getAuthenticated } from '../selectors/authentication'

import { AppThunkDispatch } from '../types'

import PostList from '../components/post-list'

const Timeline: FC = () => {
    const authenticated = useSelector(getAuthenticated)
    const posts = useSelector(getTimeline)
    const dispatch = useDispatch<AppThunkDispatch>()
    const history = useHistory()

    useEffect(() => {
        const init = async () => {
            try {
                await dispatch(fetchTimeline())
            } catch (err) {
                handleApiError(err, dispatch, history)
            }
        }

        if (authenticated) init()
    }, [authenticated])

    return <PostList posts={posts} />
}

export default Timeline
