import { DataSourceSchema, DataSourceType, DataSourceItem } from '../types';

export class DataSource {
  type: DataSourceType;
  items: Array<DataSourceItem> = [];
  constructor(schema: DataSourceSchema) {
    const { type, items = [] } = schema;
    this.type = type;
    this.items = items;
  }

  add(item: DataSourceItem) {
    this.items.push(item);
  }

  update(item: DataSourceItem) {
    const index = this.items.findIndex((n) => n.id === item.id);
    if (index > -1) {
      this.items.splice(index, 1, item);
    }
  }

  replace(id: string, item: DataSourceItem) {
    const index = this.items.findIndex((n) => n.id === id);
    if (index > -1) {
      this.items.splice(index, 1, item);
    }
  }

  remove(id: string) {
    const index = this.items.findIndex((n) => n.id === id);
    if (index > -1) {
      this.items.splice(index, 1);
    }
  }

  toSchema() {
    const { type, items } = this;
    return {
      type,
      items
    };
  }
}
