// @flow

import React from 'react'
import {ScrollView} from 'react-native'
import type {BusLineType} from './types'
import {BusLine} from './bus-line'
import moment from 'moment-timezone'
import {NoticeView} from '../../components/notice'
import type {TopLevelViewPropsType} from '../../types'
import delay from 'delay'
import {reportNetworkProblem} from '../../../lib/report-network-problem'

import * as defaultData from '../../../../docs/bus-times.json'

const TIMEZONE = 'America/Winnipeg'

const GITHUB_URL = 'https://stodevx.github.io/AAO-React-Native/bus-times.json'

export class BusView extends React.PureComponent {
  props: TopLevelViewPropsType & {
    line: string,
  }

  state = {
    busLines: defaultData.data,
    intervalId: 0,
    now: moment.tz(TIMEZONE),
  }

  componentWillMount() {
    this.fetchData()
    // This updates the screen every five seconds, so that the "next bus"
    // times are updated without needing to leave and come back.
    this.setState(() => ({intervalId: setInterval(this.updateTime, 5000)}))
  }

  componentWillUnmount() {
    clearTimeout(this.state.intervalId)
  }

  fetchData = async () => {
    const start = Date.now()
    this.setState(() => ({loading: true}))

    let {data: busLines} = await fetchJson(GITHUB_URL).catch(err => {
      reportNetworkProblem(err)
      return defaultData
    })

    // if (process.env.NODE_ENV === 'development') {
    //   busLines = defaultData.data
    // }

    this.updateTime()

    // wait 0.5 seconds – if we let it go at normal speed, it feels broken.
    const elapsed = start - Date.now()
    if (elapsed < 500) {
      await delay(500 - elapsed)
    }

    this.setState(() => ({busLines, loading: false}))
  }

  updateTime = () => {
    this.setState(() => ({now: moment.tz(TIMEZONE)}))
  }

  openMap = () => {
    const activeBusLine = this.findLine()
    this.props.navigation.navigate('BusMapView', {line: activeBusLine})
  }

  findLine = (): ?BusLineType => {
    let {busLines} = this.state
    const {line: thisLine} = this.props
    return busLines.find(({line}) => line === thisLine)
  }

  render() {
    let {now} = this.state
    // now = moment.tz('Fri 8:13pm', 'ddd h:mma', true, TIMEZONE)
    const activeBusLine = this.findLine()

    if (!activeBusLine) {
      const lines = this.state.busLines.map(({line}) => line).join(', ')
      return (
        <NoticeView
          text={`The line "${this.props.line}" was not found among ${lines}`}
        />
      )
    }

    return (
      <ScrollView>
        <BusLine line={activeBusLine} now={now} openMap={this.openMap} />
      </ScrollView>
    )
  }
}

@@ -43,24 +43,40 @@
  %7BScrollView
+, RefreshControl
 %7D from 'reac
@@ -1810,16 +1810,292 @@
 ))%0A  %7D%0A%0A
+  refreshTime = async () =%3E %7B%0A    const start = Date.now()%0A    this.setState(() =%3E (%7Bloading: true%7D))%0A    this.updateTime()%0A    const elapsed = start - Date.now()%0A    if (elapsed %3C 500) %7B%0A      await delay(500 - elapsed)%0A    %7D%0A    this.setState(() =%3E (%7Bloading: false%7D))%0A  %7D%0A%0A
   openMa
@@ -2806,24 +2806,190 @@
  %3CScrollView
+%0A        refreshControl=%7B%0A          %3CRefreshControl%0A            onRefresh=%7Bthis.refreshTime%7D%0A            refreshing=%7Bthis.state.loading%7D%0A          /%3E%0A        %7D%0A      
 %3E%0A        %3CB

allow "refreshing" the busview, which triggers a time update