

import Object_create from '@schematize/refs/js/Object.create.mjs';
import Proxy from '@schematize/refs/js/Proxy.mjs';
import Symbol from '@schematize/refs/js/Symbol.mjs';

import EventTarget from '@schematize/instance.js/src/EventTarget.mjs';

import {
  set,
  deleteProperty,
} from './customInstance.mjs';

//------------------------------------------------------------------------------
// Create Proxy Object
//------------------------------------------------------------------------------

// createProxyObject
// create an object that is warpped by a proxy
export const createProxyObject = (obj = {}, parent) => {

  // keep reference to myself
  obj.__proxyTarget__ = obj;

  // keep references to all my children

  // implement EventTarget interface
  EventTarget(obj);

  // if it has a parent, inherit from it's parent
  if (parent) {

    // change to property descriptors
    for (let property in obj) {
      obj[property] = {
        // configurable: true, // don't want this reconfigured
        enumerable: true,
        writable: true,
        value: obj[property],
      };
    }

    // Object_setPrototypeOf(obj, parent);
    // This is faster:
    obj = Object_create(parent, obj);
    
    // reset the reference to the new object 
    obj.__proxyTarget__ = obj;
  }

  // return a proxy object
  obj = obj.__proxy__ = new Proxy(obj, {
    set: (target, property, value) => (
      set(target, property, value),
      true
    ),
    deleteProperty: (target, property) => (
      deleteProperty(target, property),
      true
    ),
  });

  return obj;
};
