/**
 * Copyright (c) 2016 - 2022 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 *
 * Mock init
 */
/* global Promise */
const defaultInitData = {
  timestamp: 0,
  stores: {},
  apis: {}
};

const mockData = {
  error: false,
  initDataValue: undefined
};

const mockError = new Error('mock error');

module.exports = {
  initCommand: function mockInitCommand (payload, handler) {
    const promise = new Promise(function (resolve, reject) {
      if (mockData.error) {
        return reject(mockError);
      }
      resolve();
    });

    return promise.then(() => {
      return handler({
        error: null
      });
    }).catch((error) => {
      return handler({
        error: error.toString()
      });
    });
  },

  initData: function mockInitData () {
    const value = typeof mockData.initDataValue === 'undefined' ?
      defaultInitData : mockData.initDataValue;

    return new Promise(function (resolve, reject) {

      if (mockData.error) {
        return reject(new Error('mock error'));
      }

      resolve(value);
    });
  },

  setEmulateError: function (error) {
    mockData.error = error;
  },

  getMockError: function () {
    return mockError;
  },

  setMockInitData: function (timestamp, stores, apis) {
    if (!timestamp && !stores && !apis) {
      mockData.initDataValue = undefined;
      return;
    }

    mockData.initDataValue = {
      timestamp,
      stores,
      apis
    };
  }
}
