// form/nc/nc-timecard/nc-timecard.js

function queryRec() {
	if (state.data == null || state.data.em == null) {
		return
	}
	let emp = rec.employee_id
	if (emp !== '') {
		emp = nc.findCaseInsensitiveRecFromArr(state.data.em.data, 'per.person_id', rec.employee_id)
	}
	const callback = function () {
		if (rec.timecard_state === 'started') {
			rec.end_time = dt.currentDate() // dt.currentDateUtc()
			rec.work_time = dt.hourDifference(rec.start_time, rec.end_time)
		}
	}
	if (emp == null || emp.per == null || emp.per.person_id === '') {
		// 				rec.employee_id = ''
		nc.callServer(
			state,
			'query',
			{
				name: 'form/nc/nc-timecard/init.json'
			},
			callback
		) // clear field values if employee was not found
	} else {
		nc.setRec(state, 'per', emp.per)
		nc.setRec(state, 'employee_id', emp.per.person_id)
		nc.callServer(
			state,
			'query/rec',
			{
				name: 'form/nc/nc-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.currentDateUtc()
				calculateWorkTime(ret.rec)
		*/
// nc.callServer(state, "input/table-code", {"table": "timec", "rec": rec, "field_name": "timec.end_time"})
function save() {
	if (rec.employee_id !== '') {
		if (rec.timecard_state === 'started') {
			rec.timecard_state = 'finish'
			rec.end_time = dt.currentDateUtc()
		} else {
			rec.timecard_state = 'started'
			rec.start_time = dt.currentDateUtc() // dt.formatDateTime(dt.currentDateUtc()),  # new Date()
			rec.end_time = rec.start_time
			rec.work_time = 0
		}
		nc.saveRecord(state, 'timec', rec)
		// if rec.timecard_state == 'finish'
		rec.employee_id = ''
		queryRec() // clear field values
	}
}
