import * as React from 'react'
import { connect, Dispatch } from 'react-redux'
import * as actions from './authActions'
import { refreshTokensNeeded } from './refreshTokens'

export interface IAuthProviderProps {
  dispatch: Dispatch<any>
  children: false | React.ReactElement<any> | null
}

class AuthProvider extends React.PureComponent<IAuthProviderProps, {}> {
  private willUnmount = false
  private tokenRefreshTimeoutId = 0

  public async componentDidMount() {
    const { dispatch } = this.props

    try {
      await dispatch(actions.authRefresh())
    } catch (err) {
      // tslint:disable-next-line no-console
      console.error(err)
      await dispatch(actions.authLogout())
    } finally {
      dispatch(actions.authInit())
    }

    const refreshLoop = () => {
      if (!this.willUnmount) {
        window.setTimeout(() => {
          if (refreshTokensNeeded()) {
            dispatch(actions.authRefresh())
              .catch(() => {
                // ignore
              })
              .then(() => refreshLoop())
          } else {
            refreshLoop()
          }
        }, 1000)
      }
    }
    refreshLoop()
  }

  public componentWillUnmount() {
    this.willUnmount = true
    window.clearInterval(this.tokenRefreshTimeoutId)
  }

  public render() {
    const { children } = this.props
    return children
  }
}

export default connect()(AuthProvider)
