/**
 @example
    let tutor = new CloudObject("Tutor")
    tutor.set({
        name:"宋教练",
        age:22,
        gender:"女"
    })
    tutor.save()

    let food = new CloudObject("FoodMenu")
    food.set({
        title:"馅饼",
        price:10,
    })
    food.save()

 */
class CloudObject {
    className
    objectId
    data = {}
    constructor(className) {
        this.className = className
    }
    set(data) {
        Object.keys(data).forEach(key => {
            this.data[key] = data[key]
        })
    }
    async save() {
        let method = "POST"
        let url = "http://dev.fmode.cn:1337/parse/classes/" + this.className
        if (this.objectId) {
            method = "PUT"
            url = url + "/" + this.objectId
        }
        delete this.data.createdAt
        delete this.data.updatedAt
        delete this.data.objectId

        let response = await fetch(url, {
            "headers": {
                "content-type": "text/plain;charset=UTF-8",
                "x-parse-application-id": "dev"
            },
            "body": JSON.stringify(this.data),
            "method": method,
            "mode": "cors",
            "credentials": "omit"
        });
        let data = await response.json()
        this.objectId = data.objectId
    }

    async destroy() {
        let url = "http://dev.fmode.cn:1337/parse/classes/" + this.className + "/" + this.objectId

        let response = await fetch(url, {
            "headers": {
                "content-type": "text/plain;charset=UTF-8",
                "x-parse-application-id": "dev"
            },
            "body": null,
            "method": "DELETE",
            "mode": "cors",
            "credentials": "omit"
        });
        let data = await response.json()
        this.objectId = data.objectId
    }
}

module.exports.CloudObject = CloudObject