1import * as React from 'react'
2import * as Container from '../../util/container'
3import * as Tracker2Gen from '../../actions/tracker2-gen'
4import UnconnectedFollowButton from '../../profile/user/actions/follow-button'
5import * as Tracker2Constants from '../../constants/tracker2'
6
7type FollowProps = {
8  username: string
9  small?: boolean
10}
11const getFollowWaitingKey = (username: string) => `settings:followButton:${username}`
12
13export const FollowButton = (props: FollowProps) => {
14  const {username} = props
15  const dispatch = Container.useDispatch()
16  const userDetails = Container.useSelector(state => Tracker2Constants.getDetails(state, username))
17  const followThem = Container.useSelector(state => Tracker2Constants.followThem(state, username))
18  const followsYou = Container.useSelector(state => Tracker2Constants.followsYou(state, username))
19  const {guiID} = userDetails
20
21  React.useEffect(() => {
22    if (!guiID) {
23      dispatch(
24        Tracker2Gen.createShowUser({
25          asTracker: false,
26          skipNav: true,
27          username: username,
28        })
29      )
30    }
31  }, [username, guiID, dispatch])
32
33  const onFollow = React.useCallback(() => dispatch(Tracker2Gen.createChangeFollow({follow: true, guiID})), [
34    dispatch,
35    guiID,
36  ])
37  const onUnfollow = React.useCallback(
38    () => dispatch(Tracker2Gen.createChangeFollow({follow: false, guiID})),
39    [dispatch, guiID]
40  )
41
42  const waitingKey = React.useMemo(
43    () => [getFollowWaitingKey(username), Tracker2Constants.profileLoadWaitingKey],
44    [username]
45  )
46
47  return (
48    <UnconnectedFollowButton
49      disabled={userDetails.username !== username}
50      following={followThem}
51      followsYou={followsYou}
52      waitingKey={waitingKey}
53      small={props.small}
54      onFollow={onFollow}
55      onUnfollow={onUnfollow}
56    />
57  )
58}
59