// form/manager/timecard/timecard.js
/* global nc, dt */

const timecard = {}
const ret = {
	name: "Timecard",
	created() {
		// let id = nc.searchParameter("id")
		// nc.callServer(this, "form/manager/timecard", { "parameter": { "session_id": id } })
		// debugger
		// this.vm = this
		nc.callServer(this, "query", { "name": "form/manager/timecard/init.json" })
	},
	methods: timecard
}

timecard.queryRec = function () {
	if (this.data == null || this.data.em == null) {
		return
	}
	let rec = this.rec
	let emp = rec.employee_id
	if (emp !== "") {
		emp = nc.findCaseInsensitiveRecFromArr(this.data.em.data, "per.person_id", rec.employee_id)
	}
	const callback = function (ret) {
		if (ret.rec && ret.rec.timec)
			rec = ret.rec.timec
		if (rec.timecard_state === 'started') {
			rec.end_time = dt.currentDate()
			rec.work_time = dt.hourDifference(rec.start_time, rec.end_time)
		}
	}
	if (emp == null || emp.per == null || emp.per.person_id === "") {
		debugger
		rec.employee_id = ""
		nc.callServer(this, "query", {
			"name": "form/manager/timecard/init.json"
		}, callback) // clear field values if employee was not found
	} else {
		// nc.setRecData(rec, "per.name", emp.per.name)
		// nc.setRecData(rec, "employee_id", emp.per.person_id)
		// this.$set(rec, 'per', Object.assign({}, rec.per))
		// this.$set(rec, 'timec', Object.assign({}, rec.timec))
		// nc.setRec(this, "per.name", emp.per.name)
		nc.setRec(this, "per", emp.per)
		nc.setRec(this, "employee_id", emp.per.person_id)
		nc.callServer(this, "query/rec", {
			"name": "form/manager/timecard/query/employee.json",
			"parameter": {
				"employee": rec.employee_id,
				"option": "empty-record",
				"default": {
					timec: {
						employee_id: rec.employee_id
					}
				},
				"script": "timec.employee_id"
			}
		}, callback)
	}
}
/*
callback = (ret) ->
	if ret and ret.rec and ret.rec.timecard_state == 'started'
		ret.rec.end_time = dt.currentDate()
		timecard.calculateWorkTime(ret.rec)
*/
// nc.callServer(this, "input/script", {"table": "timec", "rec": rec, "field_name": "timec.end_time"})
timecard.save = function () {
	const rec = this.rec
	debugger
	if (rec && rec.employee_id !== "") {
		if (rec.timecard_state === 'started') {
			rec.timecard_state = 'finished'
			rec.end_time = dt.currentDate()
		} else {
			rec.timecard_state = 'started'
			rec.start_time = dt.currentDate() // dt.formatDateTime(dt.currentDate()),  # new Date()
			rec.end_time = rec.start_time
			rec.work_time = 0
		}
		nc.saveRecord(this, "timec", rec)
		// if rec.timecard_state == 'finished'
		rec.employee_id = ""
		timecard.queryRec() // clear field values
	}
}

return ret
