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

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

  exportObj = {
    // Create base64 encoded bookmarkData for accessible filePath.
    // This method will throw if error occurs
    // argument:
    //   filePath: String
    // return:
    //   bookmarkData: string
    createBookmarkDataForSecurityScopedResource(filePath) {
      var result = OSXApi.sbCreateBookmarkDataForSecurityScopedResource(filePath)
      if (typeof result === 'string') {
        throw new Error(result)
      }
      return result.bookmarkData || ''
    },

    // Convert bookmarkData to filePath. This method will implicitly renew the bookmarkData
    // This method will throw if error occurs
    // argument:
    //   bookmarkData: String
    // return:
    //   {
    //     newBookmarkData: string,  // might be empty
    //     filePath: string
    //   }
    resolveBookmarkDataForSecurityScopedResource(bookmarkData) {
      var result = OSXApi.sbResolveBookmarkDataForSecurityScopedResource(bookmarkData)
      if (typeof result === 'string') {
        // An error occurred.
        throw new Error(result)
      }

      return {
        filePath: result.filePath || '',
        newBookmarkData: result.newBookmarkData || '',
      }
    },

    // Acquire access to file.
    // This method will throw if access is not granted.
    // argument:
    //   bookmarkData: String
    // return:
    //   stopAccessingSecurityScopedResource: Function
    startAccessingSecurityScopedResource(bookmarkData) {
      let result = OSXApi.sbStartAccessingSecurityScopedResource(bookmarkData)
      if (result === false) {
        throw new Error('OperationFailed')
      }

      if (typeof result === 'string') {
        throw new Error(result)
      }

      let stopAccessingSecurityScopedResource = function() {
        OSXApi.sbStopAccessingSecurityScopedResource(bookmarkData)
      }

      return stopAccessingSecurityScopedResource
    },

  }

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

module.exports = exportObj
