/* @flow */
'use strict'

import Relay from 'react-relay'
import React from 'react'
import { ScrollView, StyleSheet, View } from 'react-native'

import metaphysics from '../../../metaphysics'

import Spinner from '../../spinner'
import SectionTitle from '../section_title'
import ArtistCard from './artist_card'
import Separator from '../../separator'

class ArtistRail extends React.Component {
  state: {
    artists: [Object],
  }

  constructor(props) {
    super(props)
    this.state = {
      artists: []
    }
  }

  componentDidMount() {
    this.props.relay.setVariables({ fetchContent: true })
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.rail.results) {
      this.setState({ artists: nextProps.rail.results })
    }
  }

  /**
   * Removes the followed artist from the list and re-renders.
   */
  handleFollowChange(artist) {
    const artists = this.state.artists.slice(0)
    const index = artists.indexOf(artist)

    metaphysics(suggestedArtistQuery(artist._id))
      .then(({ me: { suggested_artists }}) => {
        const suggested_artist = suggested_artists[0]
        if (suggested_artist) {
          // Replace the followed artist with the suggested one.
          artists[index] = suggested_artist
        } else {
          // In case of no suggestions, just remove the card
          artists.splice(index, 1)
        }
        this.setState({ artists })
      })
      .catch(error => {
        __DEV__ ? console.error(error) : console.log(error)
        // In case of an error, just remove the card.
        artists.splice(index, 1)
        this.setState({ artists })
      })
  }

  renderModuleResults() {
    if (this.state.artists.length > 0) {
      return this.state.artists.map(artist => {
        // Compose key, because an artist may appear twice on the home view in different modules.
        const key = this.props.rail.__id + artist.__id
        return <ArtistCard key={key} artist={artist} onFollow={() => this.handleFollowChange(artist)} />
      })
    } else {
      return <Spinner style={{ flex: 1 }} />
    }
  }

  title() {
    switch (this.props.rail.key) {
      case 'TRENDING':
        return 'Artists to Follow: Trending'
      case 'SUGGESTED':
        return 'Artists to Follow: Recommended for You'
      case 'POPULAR':
        return 'Artists to Follow: Popular'
    }
  }

  render() {
    return (
      <View>
        <View style={styles.title}><SectionTitle>{ this.title() }</SectionTitle></View>
        <ScrollView style={styles.cardContainer}
                    horizontal={true}
                    showsHorizontalScrollIndicator={false}
                    scrollsToTop={false}>
          {this.renderModuleResults()}
        </ScrollView>
      <Separator style={{marginTop: 5}}/>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  cardContainer: {
    flex: 1,
    flexDirection: 'row',
    marginTop: 10,
    minHeight: 330,
    marginRight: 15,
  },
  title: {
    marginLeft: 30,
    marginRight: 30,
    marginTop: 15,
    marginBottom: 10
  }
})

export default Relay.createContainer(ArtistRail, {
  initialVariables: {
    fetchContent: false,
  },

  fragments: {
    rail: () => Relay.QL`
      fragment on HomePageArtistModule {
        __id
        key
        results @include(if: $fetchContent) {
          _id
          __id
          ${ArtistCard.getFragment('artist')}
        }
      }
    `,
  }
})

function suggestedArtistQuery(artist_id: string): string {
  return `
    query {
      me {
        suggested_artists(artist_id: "${artist_id}",
                          size: 1,
                          exclude_followed_artists: true,
                          exclude_artists_without_forsale_artworks: true) {
          _id
          __id
          ${ArtistCard.artistQuery}
        }
      }
    }
  `
}

@@ -856,99 +856,8 @@
 ) %7B%0A
-    const artists = this.state.artists.slice(0)%0A    const index = artists.indexOf(artist)%0A%0A
     
@@ -951,43 +951,8 @@
 ) =%3E
- %7B%0A        const suggested_artist =
  sug
@@ -968,25 +968,25 @@
 tists%5B0%5D
-%0A
+)
         
 if (sugg
@@ -981,96 +981,168 @@
     
-if (suggested_artist) %7B%0A          // Replace the followed artist with the suggested one.
+// return artist or undefined%0A      .catch(error =%3E __DEV__ ? console.error(error) : console.log(error)) // return undefined%0A      .then((suggested_artist) =%3E %7B
 %0A   
@@ -1146,25 +1146,29 @@
         
- 
+const
  artists
 %5Bindex%5D 
@@ -1163,147 +1163,197 @@
 ists
-%5Bindex%5D = suggested_artist%0A        %7D else %7B%0A          // In case of no suggestions, just remove the card%0A          artists.splice(index, 1)
+ = this.state.artists.slice(0)                        // copy array%0A        const index = artists.indexOf(artist)%0A        if (suggested_artist) %7B%0A          artists%5Bindex%5D = suggested_artist
 %0A   
@@ -1354,24 +1354,31 @@
 st%0A        %7D
+ else %7B
 %0A        thi
@@ -1378,214 +1378,114 @@
     
-this.setState(%7B artists %7D)%0A
+  artists.splice(index, 1)
       
-%7D)%0A
       
-.catch(error =%3E %7B%0A        __DEV__ ? console.error(error) : console.log(error)%0A        // In case of an error, just remove the card.%0A        artists.splice(index, 1)
+                             // remove card when undefined%0A        %7D
 %0A   

Make following multiple in parallel work.