import FWAdapter from '@bennerinformatics/ember-fw/adapters/fw';
import {inject} from '@ember/service';
import EmberError from '@ember/error';
import {isNone, isEmpty} from '@ember/utils';

/**
 * Extension of the [base FW adapter](https://linformatics.bitbucket.io/docs/addons/client-api/ember-fw/classes/FwAdapter.html) for models that need to be fetched from a
 * non-dependency app. The reason for the difference is that if it is a non-dependency app, you need to handle the possibility that that app is not currently installed on
 * your current system, and use the model accordingly. This also means that you will need to define specifically the `appId` for the app this is the model of. This is used much
 * less commonly than the FwAppAdapter, so it will have varied use cases (ie using Tally models in Substitutions or EmployeeDb models in Message Center). Again, your file will need to
 * be named identically as the model you are copying, then you set up that adapter like this:
 *
 * ```js
 * import OptionalAppAdapter from '@bennerinformatics/ember-fw-gc/adapters/fw-optional-app';
 *
 * export default OptionalAppAdapter.extend({
 *      appId: 'empdb'
 * });
 * ```
 *
 * Provided you have the model file setup right, it should now pull the data from the optional app instead of your base app.
 *
 * @class OptionalAppAdapter
 * @extends FWAdapter
 * @module Miscellaneous
 */
export default FWAdapter.extend({
    /**
     * ID of the app containing this model
     * @type {string}
     * @prop appId
     */

    appMeta: inject(),

    host: '',

    // Override the base ajax function to add the app meta before any network requests are called
    ajax(url, type, options) {
        if (isNone(this.get('appId'))) {
            throw new EmberError('Please define your appId within your model adapter!');
        }
        // this._super is undefined within the promise, so set parent to the super function and bind the current context
        let parent = this._super.bind(this);
        return this.get('appMeta').findMeta(this.get('appId')).then((meta) => {
            if (isEmpty(meta)) {
                throw new EmberError(`App ${this.get('appId')} not found!`);
            }
            return parent(`${meta.get('apiUrl')}${url}`, type, options);
        });
    }
});