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

/*
 * This file exports OSX apis. In non OSX system, all apis will throw NotAvailable error.
 */

let exportObj

function replaceRange( s, start, length, substitute ) {
  return s.substring( 0, start ) + substitute + s.substring( start + length )
}

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

  exportObj = {
    nlpTokenize( input ) {
      // if ( !OSX10_13 ) { throw new Error( 'NotAvailable' ) }
      return OSXApi.nlpTokenize( input )
    },

    // Convert the string to normalized form (convert stemming/lemmatization to common base form)
    nlpNormalize( input ) {
      // if ( !OSX10_13 ) { throw new Error( 'NotAvailable' ) }
      let output = input
      const results = OSXApi.nlpTokenize( input )

      let offset = 0
      for ( let r of results ) {
        if ( r.lemma ) {
          output = replaceRange( output, r.start + offset, r.length, r.lemma )
          offset += r.lemma.length - r.length
        }
      }

      return output
    }
  }

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

module.exports = exportObj
