'use strict';

/*!
 * Module dependencies.
 */

const ArrayMethods = require('../array/methods');
const DocumentArrayMethods = require('./methods');

const arrayAtomicsSymbol = require('../../helpers/symbols').arrayAtomicsSymbol;
const arrayAtomicsBackupSymbol = require('../../helpers/symbols').arrayAtomicsBackupSymbol;
const arrayParentSymbol = require('../../helpers/symbols').arrayParentSymbol;
const arrayPathSymbol = require('../../helpers/symbols').arrayPathSymbol;
const arraySchemaSymbol = require('../../helpers/symbols').arraySchemaSymbol;

const _basePush = Array.prototype.push;
const numberRE = /^\d+$/;
/**
 * DocumentArray constructor
 *
 * @param {Array} values
 * @param {string} path the path to this array
 * @param {Document} doc parent document
 * @api private
 * @return {MongooseDocumentArray}
 * @inherits MongooseArray
 * @see https://bit.ly/f6CnZU
 */

function MongooseDocumentArray(values, path, doc, schematype) {
  const __array = [];

  const internals = {
    [arrayAtomicsSymbol]: {},
    [arrayAtomicsBackupSymbol]: void 0,
    [arrayPathSymbol]: path,
    [arraySchemaSymbol]: void 0,
    [arrayParentSymbol]: void 0
  };

  if (Array.isArray(values)) {
    if (values[arrayPathSymbol] === path &&
        values[arrayParentSymbol] === doc) {
      internals[arrayAtomicsSymbol] = Object.assign({}, values[arrayAtomicsSymbol]);
    }
    values.forEach(v => {
      _basePush.call(__array, v);
    });
  }
  internals[arrayPathSymbol] = path;
  internals.__array = __array;

  if (doc?.$__) {
    internals[arrayParentSymbol] = doc;
    internals[arraySchemaSymbol] = doc.$__schema.path(path);

    // `schema.path()` doesn't drill into nested arrays properly yet, see
    // gh-6398, gh-6602. This is a workaround because nested arrays are
    // always plain non-document arrays, so once you get to a document array
    // nesting is done. Matryoshka code.
    while (internals[arraySchemaSymbol] != null &&
        internals[arraySchemaSymbol].$isMongooseArray &&
        !internals[arraySchemaSymbol].$isMongooseDocumentArray) {
      internals[arraySchemaSymbol] = internals[arraySchemaSymbol].embeddedSchemaType;
    }
  }

  const proxy = new Proxy(__array, {
    get: function(target, prop) {
      if (prop === 'isMongooseArray' ||
          prop === 'isMongooseArrayProxy' ||
          prop === 'isMongooseDocumentArray' ||
          prop === 'isMongooseDocumentArrayProxy') {
        return true;
      }
      if (Object.hasOwn(internals, prop)) {
        return internals[prop];
      }
      if (Object.hasOwn(DocumentArrayMethods, prop)) {
        return DocumentArrayMethods[prop];
      }
      if (schematype?.virtuals && Object.hasOwn(schematype.virtuals, prop)) {
        return schematype.virtuals[prop].applyGetters(undefined, target);
      }
      if (Object.hasOwn(ArrayMethods, prop)) {
        return ArrayMethods[prop];
      }

      return __array[prop];
    },
    set: function(target, prop, value) {
      if (typeof prop === 'string' && numberRE.test(prop)) {
        DocumentArrayMethods.set.call(proxy, prop, value, false);
      } else if (Object.hasOwn(internals, prop)) {
        internals[prop] = value;
      } else if (schematype?.virtuals && Object.hasOwn(schematype.virtuals, prop)) {
        schematype.virtuals[prop].applySetters(value, target);
      } else {
        __array[prop] = value;
      }

      return true;
    }
  });

  return proxy;
}

/*!
 * Module exports.
 */

module.exports = MongooseDocumentArray;
