"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports["default"] = void 0;
var _lodash = require("lodash");
var _element = _interopRequireDefault(require("./element"));
var _field = _interopRequireDefault(require("./field"));
var _indexes = _interopRequireDefault(require("./indexes"));
var _config = require("./config");
var _utils = require("./utils");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); Object.defineProperty(subClass, "prototype", { writable: false }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
var Table = /*#__PURE__*/function (_Element) {
  _inherits(Table, _Element);
  var _super = _createSuper(Table);
  function Table() {
    var _this;
    var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
      name = _ref.name,
      alias = _ref.alias,
      note = _ref.note,
      _ref$fields = _ref.fields,
      fields = _ref$fields === void 0 ? [] : _ref$fields,
      _ref$indexes = _ref.indexes,
      indexes = _ref$indexes === void 0 ? [] : _ref$indexes,
      _ref$schema = _ref.schema,
      schema = _ref$schema === void 0 ? {} : _ref$schema,
      token = _ref.token,
      headerColor = _ref.headerColor,
      _ref$noteToken = _ref.noteToken,
      noteToken = _ref$noteToken === void 0 ? null : _ref$noteToken,
      _ref$partials = _ref.partials,
      partials = _ref$partials === void 0 ? [] : _ref$partials;
    _classCallCheck(this, Table);
    _this = _super.call(this, token);
    _this.name = name;
    _this.alias = alias;
    _this.note = note ? (0, _lodash.get)(note, 'value', note) : null;
    _this.noteToken = note ? (0, _lodash.get)(note, 'token', noteToken) : null;
    _this.headerColor = headerColor;
    _this.fields = [];
    _this.indexes = [];
    _this.schema = schema;
    _this.partials = partials;
    _this.dbState = _this.schema.dbState;
    _this.generateId();
    _this.processFields(fields);
    // Process partials after fields to get injected fields' orders
    // Process partials before indexes for indexes to properly check all owned and injected columns
    _this.processPartials();
    _this.processIndexes(indexes);
    return _this;
  }
  _createClass(Table, [{
    key: "generateId",
    value: function generateId() {
      this.id = this.dbState.generateId('tableId');
    }
  }, {
    key: "processFields",
    value: function processFields(rawFields) {
      var _this2 = this;
      if (rawFields.length === 0) {
        this.error('Table must have at least one field');
      }
      rawFields.forEach(function (field) {
        _this2.pushField(new _field["default"](_objectSpread(_objectSpread({}, field), {}, {
          table: _this2
        })));
      });
    }
  }, {
    key: "pushField",
    value: function pushField(field) {
      this.checkField(field);
      this.fields.push(field);
    }
  }, {
    key: "checkField",
    value: function checkField(field) {
      if (this.fields.some(function (f) {
        return f.name === field.name;
      })) {
        field.error("Field \"".concat(field.name, "\" existed in table ").concat((0, _utils.shouldPrintSchema)(this.schema) ? "\"".concat(this.schema.name, "\".") : '', "\"").concat(this.name, "\""));
      }
    }
  }, {
    key: "processIndexes",
    value: function processIndexes(rawIndexes) {
      var _this3 = this;
      rawIndexes.forEach(function (index) {
        _this3.pushIndex(new _indexes["default"](_objectSpread(_objectSpread({}, index), {}, {
          table: _this3
        })));
      });
    }
  }, {
    key: "pushIndex",
    value: function pushIndex(index) {
      this.checkIndex(index);
      this.indexes.push(index);
    }
  }, {
    key: "checkIndex",
    value: function checkIndex(index) {
      var _this4 = this;
      index.columns.forEach(function (column) {
        if (column.type === 'column' && !_this4.findField(column.value)) {
          index.error("Column \"".concat(column.value, "\" do not exist in table ").concat((0, _utils.shouldPrintSchema)(_this4.schema) ? "\"".concat(_this4.schema.name, "\".") : '', "\"").concat(_this4.name, "\""));
        }
      });
    }
  }, {
    key: "findField",
    value: function findField(fieldName) {
      return this.fields.find(function (f) {
        return f.name === fieldName;
      });
    }
  }, {
    key: "checkSameId",
    value: function checkSameId(table) {
      return this.schema.checkSameId(table.schemaName || _config.DEFAULT_SCHEMA_NAME) && (this.name === table.name || this.alias === table.name || this.name === table.alias || this.alias && this.alias === table.alias);
    }
  }, {
    key: "processPartials",
    value: function processPartials() {
      var _this$partials,
        _this5 = this;
      if (!((_this$partials = this.partials) !== null && _this$partials !== void 0 && _this$partials.length)) return;
      /**
       * When encountering conflicting columns or settings with identical names, the following resolution order is applied:
       * 1. Local Table Definition: If a definition exists within the local table, it takes precedence.
       * 2. Last Partial Definition: If no local definition is found,
       *  the definition from the last partial (in dbml source) containing the conflicting name is used.
       *
       * each partial has the following structure:
       * {
       *   name: string,
       *   order: number, // determine where the partials fields will be injected in comparison with the table fields and other partials
       *   token, // token of the partial definition
       * }
       */
      var existingFieldNames = new Set(this.fields.map(function (f) {
        return f.name;
      }));
      var existingSettingNames = new Set();
      if (!(0, _lodash.isNil)(this.note)) existingSettingNames.add('note');
      if (!(0, _lodash.isNil)(this.headerColor)) existingSettingNames.add('headerColor');

      // descending order, we'll inserted the partial fields from tail to head
      var sortedPartials = this.partials.sort(function (a, b) {
        return b.order - a.order;
      });

      // insert placeholder into table.fields
      sortedPartials.toReversed().forEach(function (partial) {
        _this5.fields.splice(partial.order, 0, 'dummy');
      });
      sortedPartials.forEach(function (partial) {
        var tablePartial = _this5.schema.database.findTablePartial(partial.name);
        if (!tablePartial) _this5.error("Table partial ".concat(partial.name, " not found"), partial.token);
        partial.id = tablePartial.id;
        if (tablePartial.fields) {
          var _this5$fields;
          // ignore fields that already exist in the table, or have been added by a later partial
          var rawFields = tablePartial.fields.filter(function (f) {
            return !existingFieldNames.has(f.name);
          });
          var fields = rawFields.map(function (rawField) {
            existingFieldNames.add(rawField.name);

            // convert inline_refs from injected fields to refs
            if (rawField.inline_refs) {
              rawField.inline_refs.forEach(function (iref) {
                var _this5$schema;
                var ref = {
                  token: rawField.token,
                  endpoints: [{
                    tableName: _this5.name,
                    schemaName: (_this5$schema = _this5.schema) === null || _this5$schema === void 0 ? void 0 : _this5$schema.name,
                    fieldNames: [rawField.name],
                    relation: ['-', '<'].includes(iref.relation) ? '1' : '*',
                    token: rawField.token
                  }, {
                    tableName: iref.tableName,
                    schemaName: iref.schemaName,
                    fieldNames: iref.fieldNames,
                    relation: ['-', '>'].includes(iref.relation) ? '1' : '*',
                    token: iref.token
                  }],
                  injectedPartial: tablePartial
                };
                // The global array containing references with 1 endpoint being a field injected from a partial to a table
                _this5.schema.database.injectedRawRefs.push(ref);
              });
            }
            return new _field["default"](_objectSpread(_objectSpread({}, rawField), {}, {
              noteToken: null,
              table: _this5,
              injectedPartial: tablePartial,
              injectedToken: partial.token
            }));
          });
          (_this5$fields = _this5.fields).splice.apply(_this5$fields, [partial.order, 1].concat(_toConsumableArray(fields)));
        } else {
          _this5.fields.splice(partial.order, 1); // still need to remove the dummy element, even when there's no field in the partial
        }

        // merge settings
        if (!existingSettingNames.has('note') && !(0, _lodash.isNil)(tablePartial.note)) {
          _this5.noteToken = null;
          _this5.note = tablePartial.note;
          existingSettingNames.add('note');
        }
        if (!existingSettingNames.has('headerColor') && !(0, _lodash.isNil)(tablePartial.headerColor)) {
          _this5.headerColor = tablePartial.headerColor;
          existingSettingNames.add('headerColor');
        }

        // merge indexes
        tablePartial.indexes.forEach(function (index) {
          _this5.indexes.push(new _indexes["default"](_objectSpread(_objectSpread({}, index), {}, {
            table: _this5,
            injectedPartial: tablePartial
          })));
        });
      });
    }
  }, {
    key: "export",
    value: function _export() {
      return _objectSpread(_objectSpread({}, this.shallowExport()), this.exportChild());
    }
  }, {
    key: "exportChild",
    value: function exportChild() {
      return {
        fields: this.fields.map(function (f) {
          return f["export"]();
        }),
        indexes: this.indexes.map(function (i) {
          return i["export"]();
        })
      };
    }
  }, {
    key: "exportChildIds",
    value: function exportChildIds() {
      return {
        fieldIds: this.fields.map(function (f) {
          return f.id;
        }),
        indexIds: this.indexes.map(function (i) {
          return i.id;
        })
      };
    }
  }, {
    key: "exportParentIds",
    value: function exportParentIds() {
      return {
        schemaId: this.schema.id,
        groupId: this.group ? this.group.id : null
      };
    }
  }, {
    key: "shallowExport",
    value: function shallowExport() {
      return {
        name: this.name,
        alias: this.alias,
        note: this.note,
        headerColor: this.headerColor,
        partials: this.partials
      };
    }
  }, {
    key: "normalize",
    value: function normalize(model) {
      model.tables[this.id] = _objectSpread(_objectSpread(_objectSpread({
        id: this.id
      }, this.shallowExport()), this.exportChildIds()), this.exportParentIds());
      this.fields.forEach(function (field) {
        return field.normalize(model);
      });
      this.indexes.forEach(function (index) {
        return index.normalize(model);
      });
    }
  }]);
  return Table;
}(_element["default"]);
var _default = Table;
exports["default"] = _default;