import {concat, deepClone, error} from "../../core";

function State(name, data) {
    this.name = name
    Object.defineProperty(this, '__data', {
        value: deepClone(data),
        enumerable: false,
        configurable: false,
        writable: false
    })
    Object.defineProperty(this, 'subscribers', {
        value: [],
        writable: false,
        configurable: false,
    })
    Object.defineProperty(this, 'reducers', {
        value: {},
        writable: false,
        configurable: false
    })
    Object.defineProperty(this, 'data', {
        get() {
            return this.__data
        },
        writable: false,
        configurable: false
    })
}

State.prototype.write = function (fieldName, changes) {
    concat(this.data[fieldName], changes, true)
}

State.prototype.read = function (fieldName) {
    return this.data[fieldName]
}

/**
 * @param {function(action: String, state: Object): Object} reducer
 */
State.prototype.defineReducer = function (reducer) {
    if (this.reducers.indexOf(reducer)<0) this.reducers.push(reducer)
    else error('Reducer already defined', reducer)
}

State.prototype.subscribe =  function (callback) {
    this.subscribers.push(callback)
}

State.prototype.unsubscribe = function (callback) {
    this.subscribers.splice(this.subscribers.findIndex((cb)=>cb===callback))
}

State.prototype.dispatch = function (action, data) {

}