context = window
MIX_MODES = context.JK.MIX_MODES

@PayPalConfirmationScreen = React.createClass({

  mixins: [Reflux.listenTo(@AppStore, "onAppInit"), Reflux.listenTo(@UserStore, "onUserChanged")]

  render: () ->
    content = null


    if this.state.sold

      if context.jamClient && context.jamClient.IsNativeClient()
        platformMessage = `<div>
          <p> To play your purchased JamTrack, start a session and then open the JamTrack</p>
          <a className="download-jamkazam-wrapper" href="/client#/createSession">
            <div className="download-jamkazam">
              Click Here to Start a Session
            </div>
          </a>
        </div>`
      else
        platformMessage =
          `<div>
            <a href='/client#/jamtrack' className="download-jamkazam-wrapper jt-popup">
              <div className="download-jamkazam">
                Click Here to Start Using Your JamTrack
              </div>
            </a>
            <a href='/downloads' rel="external" className="download-jamkazam-wrapper" target="_blank">
              <div>
                Do More With Your JamTrack - Click Here to Download Our Application
              </div>
            </a>
            <a className="back-to-browsing" href="/client#/jamtrack">
              or click here to browse more jamtracks
            </a>
          </div>`
      content = `<div className="sold-notice">
        <h2>Thank you for your order!</h2>
        {platformMessage}
      </div>`
    else
      orderButtons = {"button-orange": true, "place-order-btn": true, disabled: this.state.ordering }
      cancelButtons = {"button-grey": true, "cancel": true, disabled: this.state.ordering }

      content = `<div>
        <h2 className="confirm-header">Confirm PayPal Payment</h2>

        <p>You have not yet made a payment via PayPal. Please review your purchase and confirm or cancel.</p>

        <div className="controls">
          <a href="#" className={classNames(orderButtons)} onClick={this.placeOrder}>CONFIRM PURCHASE WITH
            PAYPAL</a>
          <a href="#" className={classNames(cancelButtons)} onClick={this.cancel}>CANCEL</a>

          <div className="clearall"/>
        </div>
        <ShoppingCartContents carts={this.state.carts}/>

        <div className="controls bottom">
          <a href="#" className={classNames(orderButtons)} onClick={this.placeOrder}>CONFIRM PURCHASE WITH
            PAYPAL</a>
          <a href="#" className={classNames(cancelButtons)} onClick={this.cancel}>CANCEL</a>

          <div className="clearall"/>
        </div>
      </div>`

    `<div className="PayPalConfirmationScreen">
      <div className="content-body-scroller">
        {content}
      </div>
    </div>`

  placeOrder: (e) ->
    e.preventDefault()
    if this.state.ordering
      return
    @setState({ordering: true})

    console.log("placing order with paypal")
    @rest.paypalPlaceOrder()
    .done((response) =>
      console.log("paypal detail obtained", response)

      @setState({sold: true, ordering: false})
      context.JK.JamTrackUtils.checkShoppingCart()
      @app.refreshUser()
    )
    .fail((jqXHR) =>
      @setState({ordering: false})
      if jqXHR.status == 404
        context.JK.Banner.showAlert('PayPal Session Over', 'Your PayPal authorization has expired.  Please restart the PayPal confirmation process. <a href="/client#/checkoutPayment">Click Here to Checkout Again.</a>')
      else if jqXHR.status == 422
        response = JSON.parse(jqXHR.responseText)
        context.JK.Banner.showAlert('PayPal Purchase Error', 'PayPal: ' + response.message)
      else
        context.JK.Banner.showAlert('PayPal/Sales Error', 'Please contact support@jamkazam.com')
    )

  cancelOrder: (e) ->
    e.preventDefault()

    window.location = '/client#/jamtrack'

  getInitialState: () ->
    {}

  componentDidMount: () ->

  componentDidUpdate: () ->

  afterShow: (data) ->
    rest.getShoppingCarts()
    .done((carts) =>
      @setState({carts: carts})
      if carts.length == 0
        window.location = '/client#/jamtrack'
        return

      @rest.paypalDetail()
      .done((response) =>
        console.log("paypal detail obtained", response)
      )
      .fail((jqXHR) =>
        if jqXHR.status == 404
          context.JK.Banner.showAlert('PayPal Session Over', 'Your PayPal authorization has expired.  Please restart the PayPal confirmation process. <a href="/client#/checkoutPayment">Click Here to Checkout Again.</a>')
        else if jqXHR.status == 422
          response = JSON.parse(jqXHR.responseText)
          context.JK.Banner.showAlert('PayPal Purchase Error', 'PayPal: ' + response.message)
        else
          context.JK.Banner.showAlert('PayPal/Sales Error', 'Please contact support@jamkazam.com')
          @app.notifyServerError jqXHR, 'PayPal Communication Error'
      )
    )
    .fail((jqXHR) =>
      @app.notifyServerError jqXHR, 'Unable to fetch carts'
    )


  beforeShow: () ->
    this.setState({sold: false})

  onAppInit: (@app) ->
    @EVENTS = context.JK.EVENTS
    @rest = context.JK.Rest()
    @logger = context.JK.logger

    screenBindings =
      'beforeShow': @beforeShow
      'afterShow': @afterShow

    @app.bindScreen('paypal/confirm', screenBindings)

  onUserChanged: (userState) ->
    @user = userState?.user

})