const CONFIG = require("../config.js");
const Parse = getApp().Parse

async function saveLog(gid, uid, className) {
    let BehaviorLog = new Parse.Query('BehaviorLog')
    BehaviorLog.equalTo('user', uid)
    BehaviorLog.equalTo('targetId', gid)
    BehaviorLog.equalTo('targetClassName', className)
    BehaviorLog.select('objectId')
    let exist = await BehaviorLog.first()
    if (exist && exist.id) {
        return
    }
    let Behavior = Parse.Object.extend('BehaviorLog')
    let behavior = new Behavior()

    if (uid) {
        behavior.set('user', {
            __type: "Pointer",
            className: "_User",
            objectId: uid
        })
    }
    behavior.set('company', {
        __type: "Pointer",
        className: "Company",
        objectId: CONFIG.default.company
    })
    behavior.set('targetId', gid)
    behavior.set('targetClassName', className)
    behavior.set('targetObject', [{ "__type": "Pointer", "className": className, "objectId": gid }])
    await behavior.save()
}

async function collect(cid, className, type, name, image, uid) {
    let Collect = Parse.Object.extend('Collect')
    let collect = new Collect()
    collect.set('collectId', cid)
    collect.set('schemaName', className)
    collect.set('collectTarget', [{
        __type: 'Pointer',
        className: className,
        objectId: cid
    }])
    collect.set('type', type)
    collect.set('name', name)
    collect.set('image', image)
    if (uid) {
        collect.set('user', {
            __type: 'Pointer',
            className: '_User',
            objectId: uid
        })
    }

    collect.set('company', {
        __type: 'Pointer',
        className: 'Company',
        objectId: CONFIG.default.company
    })
    let col = await collect.save()
    if (col && col.id) {
        return true
    } else {
        return false
    }
}

async function cancelCollect(cid, className, uid) {
    let Collect = new Parse.Query('Collect')
    Collect.equalTo('user', uid)
    Collect.equalTo('collectId', cid)
    Collect.equalTo('schemaName', className)
    Collect.equalTo('company', CONFIG.default.company)
    let collect = await Collect.first()
    if (collect) {
        await collect.destroy()
        return true

    } else {
        return false
    }

}
module.exports = {
    saveLog: saveLog,
    collect: collect,
    cancelCollect: cancelCollect,
}