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

  cancel: (callback) ->
    @invokeMethod 'cancelSubscription', callback

  terminate: (callback) ->
    @invokeMethod 'terminateSubscription', (err) =>
      return callback err  if err
      refundAmount = @calculateRefund()

      @refund refundAmount, (err) ->
        return callback err  if err
        
        callback null, refundAmount


  resume: (callback) ->

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

  upgrade: (account, oldPlan, newPlan, callback) ->
    newPlan.checkQuota @usage, {}, (err) =>
      return callback { message: 'Quota succeeded!' }  if err

      @terminate oldPlan, (err, refundAmount) =>
        return callback err  if err

        newPlan.subscribe @paymentMethodId, (err, newSubscription) =>
          return callback err  if err

          account.addSubscription newSubscription, (err) =>
            return callback err  if err
            
            newSubscription.update $set: usage: @usage, (err) ->
              return callback err  if err

              callback null, newSubscription

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

  transitionTo: secure (client, { planCode, paymentMethodId }, callback) ->
    JPaymentPlan = require './plan'
    JPaymentMethod = require './method'

    { delegate } = client.connection

    delegate.fetchPaymentMethods {},
      targetOptions: selector: { paymentMethodId }
    , (err, paymentMethods) =>
      return callback err  if err
      unless paymentMethods?.length is 1
        return callback { message: 'Unrecognized payment method!' }

      @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 delegate, oldPlan, newPlan, callback
          else
            @upgrade delegate, oldPlan, newPlan, callback
