 React = require 'react'
-PromiseToSetState = require '../lib/promise-to-set-state'
 talkClient = require '../api/talk'
+auth = require '../api/auth'
 apiClient = require '../api/client'
 Paginator = require '../talk/lib/paginator'
 SubjectViewer = require '../components/subject-viewer'

    auth.stopListening 'change', @fetchCollection

  render: ->
    if @state.collection?
      <CollectionPage {...@props} user={@state.user} collection={@state.collection} roles={@state.roles} />
    else
      <div className="content-container">
        {if @state.rejected.collection?
          <code>{@state.rejected.collection.toString()}</code>
        else
          <LoadingIndicator>
            <Translate content="collectionPage.loading" />
          </LoadingIndicator>}
      </div>


  getInitialState: ->
    collection: null
    user: null
    roles: null
    error: false
    loading: false

  propChangeHandlers:
    'params.owner': 'fetchCollection'
    'params.name': 'fetchCollection'

  fetchCollection: ->
    @setState loading: true

    auth.checkCurrent().then (user) =>
      apiClient.type('collections')
        .get(owner: @props.params?.owner, slug: @props.params?.name, include: 'owner')
        .then ([collection]) =>
          unless collection then @setState error: true

          apiClient.type('collection_roles')
            .get(collection_id: collection.id)
            .then (roles) =>
              @setState
                collection: collection
                user: user
                roles: roles
        .catch =>
          @setState error: true
        .then =>
          @setState loading: false

  componentDidMount: ->
    auth.listen 'change', @fetchCollection
