/*******************************************************
 * Copyright (C) 2018 XMind Ltd. - All Rights Reserved
 *******************************************************/

/*
 * This file exports OSX apis. In non OSX system, all apis will throw NotAvailable error.
 *
 * For InAppPurchase, please also look at:
 *   https://github.com/electron/electron/blob/2-0-x/docs/api/in-app-purchase.md
 *   https://github.com/electron/electron/blob/master/docs/api/in-app-purchase.md
 *
 * Notice:
 *   'transactions-updated' event is not implemented in this addon.
 *   Please use Electron's inAppPurchase module to listen 'transactions-updated' before
 *   calling "purchaseProduct()".
 */

let exportObj

if ( process.platform === 'darwin' ) {
  let OSXApi = require( 'bindings' )( 'addon.node' )

  exportObj = {

    // Purchase item. Please listen to 'transactions-updated' event before calling this method.
    purchaseProduct( productID, quantity, callback ) {
      OSXApi.iapPurchaseProduct( productID, quantity, callback )
    },

    getProducts( productIDs, callback ) {
      OSXApi.iapGetProducts( productIDs, callback )
    },

    canMakePayments() {
      return OSXApi.iapCanMakePayments()
    },

    getReceiptURL() {
      return OSXApi.iapGetReceiptURL()
    },

    finishAllTransactions() {
      OSXApi.iapFinishAllTransactions()
    },

    finishTransactionByDate( date ) {
      OSXApi.iapFinishTransactionByDate( date )
    },

    // Restore purchased item. This method will return a promise that will resolve when the
    // action is completed successfully.
    restoreCompletedTransactions() {
      return new Promise(function(resolve, reject){
        OSXApi.iapRestoreCompletedTransactions(function(result, error){
          if (result) {
            resolve()
          } else {
            reject(error)
          }
        })
      })
    },

    // Refresh the iap receipt. This method will return a promise that will resolve when the
    // action is completed successfully.
    refreshReceipt() {
      return new Promise(function(resolve, reject){
        OSXApi.iapRefreshReceipt(function(result, error){
          if (result) {
            resolve()
          } else {
            reject(error)
          }
        })
      })
    }
  }

} else {
  // In non-osx system. All apis are not available
  exportObj = new Proxy( {}, {
    get() { throw new Error( 'NotAvailable' ) }
  } )
}

module.exports = exportObj
