$ = jQuery
context = window
logger = context.JK.logger
rest = new context.JK.Rest()

@StripeStore = Reflux.createStore(
  {

    listenables: @StripeActions

    init: ->
      this.listenTo(context.AppStore, this.onAppInit)

    onAppInit: (@app) ->

    onConnect: (purpose, user) ->
      if purpose == 'school'
        redirect = '/client#/account/school'
      else if purpose == 'jamclass-home'
        redirect = '/client#/jamclass'
      else if purpose == 'retailer'
        redirect = '/client#/account/retailer'
      else
        throw "unknown purpose #{purpose}"

      rest.createRedirectHint({redirect_location:redirect}).done((response) => @onHintDone(response, user)).fail(@app.ajaxError)

    onHintDone: (response, user) ->
      redirectUri = encodeURIComponent(context.JK.makeAbsolute('/auth/stripe_connect/callback'))
      teacherProfileUri = encodeURIComponent(context.JK.makeAbsolute("/client#/profile/teacher/#{user.id}"))
      email = encodeURIComponent(user.email)
      firstName = encodeURIComponent(user.first_name)
      lastName = encodeURIComponent(user.last_name)

      url = "/auth/stripe_connect?redirect_uri=#{redirectUri}&scope=read_write&stripe_user[url]=#{teacherProfileUri}&stripe_user[email]=#{email}&stripe_user[first_name]=#{firstName}&stripe_user[last_name]=#{lastName}"

      # product description
      productDescription = "Online music lessons billed either per lesson or per month"
      url += "&stripe_user[product_description]=#{productDescription}"

      # business type
      url += "&stripe_user[business_type]=sole_prop"

      # business name
      businessName = "#{user.name} Lessons"
      url += "&stripe_user[business_name]=#{businessName}"

      # country
      if user.country?
        url += "&stripe_user[country]=#{encodeURIComponent(user.country)}"


      window.location.href = url
  }
)
