 module.exports = class JPaymentSubscription extends jraphical.Module
 
   {secure, dash} = require 'bongo'
-  {partition} = require '../../util'
   JUser    = require '../user'
   JPayment = require './index'
 

  credit$: secure (client, pack, callback) ->
    @debit$ client, pack, -1, callback

  upgrade: (oldPlan, newPlan, callback) ->
    @terminate (err, refundAmount) ->
      return callback err  if err

      callback null, refundAmount

  downgrade: (oldPlan, newPlan, callback) ->
    callback null, downgrade: to: newPlan, from: oldPlan

  transitionTo: secure (client, planCode, callback) ->
    JPaymentPlan = require './plan'

    { delegate } = client.connection

    @isOwnedBy delegate, (err, hasTarget) =>
      return callback err  if err
      return callback { message: 'Access denied!' }  unless hasTarget

      oldPlan = null
      newPlan = null

      queue = [
        => JPaymentPlan.fetchPlanByCode @planCode, (err, plan_) ->
          oldPlan = plan_
          queue.fin err

        -> JPaymentPlan.fetchPlanByCode planCode, (err, plan_) ->
          newPlan = plan_
          queue.fin err
      ]
      dash queue, =>
        if oldPlan.feeAmount > newPlan.feeAmount
          @downgrade oldPlan, newPlan, callback
        else
          @upgrade oldPlan, newPlan, callback

  @checkUserSubscription = secure ({connection:{delegate}}, planCode, callback)->
    throw Error 'reimplement this!'

  isOwnedBy: (account, callback) ->
    account.hasTarget this, 'service subscription', callback

  refund: (options, callback) ->
    payment.createRefund @paymentMethodId, options, callback

  calculateRefund: ->
    { max, ceil } = Math
