import API from 'api'
import utils from 'utils'

export default class Model {
	static schema = {}

	static fromArray(array) {
		return array.map(object =>
			object instanceof this
				? object
				: new this(object)
		)
	}

	static map(array, func) {
		return this.fromArray(array).map(func)
	}

	static pathFor(instance) {
		if (!instance && instance !== null)
			return console.error(`You didn't pass anything to ${this.name}.pathFor. If you want a new route, you can pass null.`)

		let resourceName = this.resourceName || utils.resourceize(this.name)
		let id = (instance && instance.id) || 'new'
		return ['', resourceName, id].join('/')
	}

	constructor(props) {
		Object.assign(this, this.constructor.schema, props)
	}

	setState(props) {
		Object.assign(this, props)
		return this
	}

	save(apiOptions) {
		return API.send(`/api/${this.toPath()}`, this, apiOptions)
				.then(response => {
					console.log(response);

					if (response.code) {
						this.errors = response.code
						throw response.code
					}

					this.setState(response)
					return this
				})
	}

	toPath() {
		return this.constructor.pathFor(this)
	}

	toString() {
		return this.toPath()
	}
}

@@ -258,38 +258,104 @@
 urn 
-this.fromArray(
 array
-)
 .map(
-func
+object =%3E%0A%09%09%09object instanceof this%0A%09%09%09%09? func(object)%0A%09%09%09%09: func(new this(object))%0A%09%09
 )%0A%09%7D
@@ -1233,11 +1233,339 @@
 ath()%0A%09%7D
+%0A%0A%09toJSON() %7B%0A%09%09let json = Object.assign(%7B%7D, this)%0A%09%09Object.keys(json).forEach(key =%3E %7B%0A%09%09%09let value = json%5Bkey%5D%0A%09%09%09if (value instanceof Model)%0A%09%09%09%09json%5Bkey%5D = %7Bid: value.id%7D%0A%0A%09%09%09if (Array.isArray(value)) %7B%0A%09%09%09%09json%5Bkey%5D = value.map(child =%3E%0A%09%09%09%09%09child instanceof Model ? %7Bid: child.id%7D : child%0A%09%09%09%09)%0A%09%09%09%7D%0A%09%09%7D)%0A%0A%09%09return json%0A%09%7D
 %0A%7D%0A

Add toJSON to Model to flatten child models to just an id when saving