// preference/form/nc/nc-production/nc-production-old.js

// plugin/capacity/capacity_vue.coffee
const popup = {}
const loc = {}

function updateJsonEditor(data) {
	// https://github.com/arvidkahl/vue-json-tree-view
	console.debug('updateJsonEditor', data)
	nc.setRec(state, 'capacity', data)
	return updateJson('to_text')
}

// return Object.assign({ updateJsonEditor, popup, state }, toRefs(state))

// loc.capGraphData = null
function init() {
	function callb(ret) {
		if (ret) {
			/* if state.popup.foreman
          state.popup.foreman.forEach (rec) ->
            rec.show = rec.value + ", " + rec.show
        */
			if (state.popup.person) {
				state.popup.person.forEach(function (rec) {
					return (rec.show = rec.value + ', ' + rec.show)
				})
			}
		}
	}
	nc.callServer(
		state,
		'query',
		{
			name: 'form/nc/nc-production/capacity_query_init.json'
		},
		callb
	)
}
function graphAreaHeight() {
	return 500
}

function gridRightAction(newValue) {
	var grid, index, newRow
	grid = state.grid && state.grid[loc.dropdownGridName]
	if (!grid) {
		return
	}
	index = (loc.dropdownEvent && loc.dropdownEvent.node.rowIndex) || -1
	// api = loc.dropdownEvent.api
	if (newValue === 'add_row') {
		loc.gridDataChanged = true
		if (loc.dropdownEvent) {
			newRow = _.cloneDeep(loc.dropdownEvent.data)
		} else {
			newRow = nc.grid.newRecord(grid)
		}
		newRow.id = grid.data.length + 1
		if (newRow.reff_record_id) {
			newRow.reff_record_id = ''
		} else if (newRow.cap_record_id) {
			newRow.cap_record_id = ''
		} else if (newRow.timec_record_id) {
			newRow.timec_record_id = ''
		}
		grid.data.push(newRow)
		console.debug('plus ' + index + ' - add row')
	} else if (newValue === 'delete_row') {
		if (!loc.dropdownEvent) {
			// todo: remove when minus is not shown
			return
		}
		loc.gridDataChanged = true
		if (loc.dropdownEvent.data) {
			loc.gridDataDeleteRec.unshift(loc.dropdownEvent.data) // add to first
		}
		// id = loc.dropdownEvent.data.reff_record_id or loc.dropdownEvent.data.cap_record_id or loc.dropdownEvent.data.timec_record_id
		// if id and id isnt ""
		// loc.gridDataDeleteRec.push(id)
		grid.data.splice(index, 1)
		console.debug('minus ' + index + ' - remove row')
	}
}

function gridRightClick(event, cellMouseEvent) {
	var dropdownValues, ref, ref1, settings
	dropdownValues = [
		{
			name: ((ref = state.hdr) != null ? ((ref1 = ref.grid) != null ? ref1.add_row : void 0) : void 0) || "<i class='far fa-plus-circle'></i><span>&nbsp;Add row</span>",
			value: 'add_row'
		}
	]
	if (cellMouseEvent) {
		dropdownValues.push({
			name: state.hdr.grid.delete_row || "<i class='far fa-minus-circle'></i><span>&nbsp;Delete row</span>",
			value: 'delete_row'
		})
	}
	if (loc.dropdown) {
		loc.dropdown.dropdown('destroy')
	} else {
		loc.dropdown = jQuery('#gridRightClickMenu')
	}
	settings = {
		// http://semantic-ui.com/modules/dropdown.html#/settings
		duration: 0,
		keepOnScreen: true,
		allowReselection: true,
		values: dropdownValues,
		onChange: function (newValue, text, $choice) {
			return gridRightAction(newValue)
		}
	}
	loc.dropdown.dropdown(settings)
	loc.dropdown.offset({
		top: event.y,
		left: event.x
	})
	loc.dropdown.dropdown('show')
	return (loc.dropdownShown = true)
}

function gridRowCallback(eventType, event, gridVm, gridName, cellMouseEvent) {
	var api, col, date, grid, i, len, node, person, rec, ref, row, shift, time
	if ((state != null ? state.grid : void 0) == null) {
		return
	}
	// mouse events in their own if - they happen very often
	console.log('gridRowCallback: ' + gridName, eventType, event, gridVm)
	if (loc.dropdownShown) {
		loc.dropdown.dropdown('hide')
		loc.dropdownShown = false
	}
	if (eventType === 'onContextMenu') {
		row = ''
		col = ''
		if (cellMouseEvent) {
			node = cellMouseEvent.node
			node.setSelected(true, true) // true, true == select row, deselect other rows
			row = node.rowIndex + 1
			col = cellMouseEvent.column.colDef.field
		}
		console.debug('onContextMenu: ' + gridName + ' - row: ' + row + ' - col: ' + col)
		loc.dropdownEvent = null
		if (gridName === 'timecard' || gridName === 'capacity' || gridName === 'resource_efficiency') {
			loc.dropdownEvent = cellMouseEvent
			loc.dropdownGridName = gridName
			gridRightClick(event, cellMouseEvent)
		}
		return false // true == show default context menu
	} else if (eventType === 'onRowClicked') {
		if (gridName === 'actual_work_phase') {
			grid = state.grid.person_shift
			if (event.data && grid) {
				date = event.data.prwo_json_data.date
				time = event.data.prwo_json_data.end_time
				shift = event.data.prwo_json_data.work_shift
				person = event.data.prwo_person_id
				ref = gridVm.data
				// find last time and it's end shift
				for (i = 0, len = ref.length; i < len; i++) {
					rec = ref[i]
					if (rec.prwo_person_id === person && rec.prwo_json_data.date === date && rec.prwo_json_data.end_time >= time) {
						time = rec.prwo_json_data.end_time
						shift = rec.prwo_json_data.work_shift
					}
				}
				api = grid.gridOptions.api
				api.forEachNodeAfterFilter(function (node) {
					if (node.data.shift_number === shift) {
						shift = null // set only first, next will go to else part
						return node.setSelected(true) // set selected, exclusively, remove any other selections
					} else {
						return node.setSelected(false)
					}
				})
			}
		}
	}
}

function selectedRows(gridName) {
	var grid, ref
	grid = state != null ? ((ref = state.grid) != null ? ref[gridName] : void 0) : void 0
	if (!grid) {
		return []
	}
	return grid.gridOptions.api.getSelectedRows()
}

function selectedNodes(gridName) {
	var grid, ref
	grid = state != null ? ((ref = state.grid) != null ? ref[gridName] : void 0) : void 0
	if (!grid) {
		return []
	}
	return grid.gridOptions.api.getSelectedNodes()
}

function changedRows(gridName) {
	var changedData, gridArr, ref
	gridArr = state != null ? ((ref = state.grid) != null ? ref[gridName].data : void 0) : void 0
	if (gridArr == null || gridArr[0] == null) {
		return
	}
	changedData = []
	gridArr.forEach(function (rec) {
		return changedData.push(rec)
	})
	// state.rec.checkmark = "x"
	// if state.rec.checkmark and state.rec.checkmark isnt ""
	// changedData.push(rec)
	return changedData
}

function save() {
	var actualNode, actualNodes, actualRec, actualRows, date, grid, preferenceName, rec, rows, saveData, shiftRec
	if (!(state != null ? state.grid : void 0)) {
		return
	}
	if (
		state.rec.state === 'actual' ||
		state.rec.state === 'checked' ||
		state.rec.state === 'timecard' ||
		state.rec.state === 'capacity' ||
		state.rec.state === 'resource_efficiency'
	) {
		grid = null
		if (state.rec.state === 'actual' || state.rec.state === 'checked') {
			grid = state.grid.person_shift
		} else {
			grid = state.grid[state.rec.state]
		}
		if (grid) {
			grid.gridOptions.api.stopEditing()
		}
		saveData = []
		preferenceName = ''
		if (state.rec.state === 'actual') {
			preferenceName = 'form/nc/nc-production/save_timecard.json'
			rows = selectedRows('person_shift')
			if (rows.length < 1) {
				return
			}
			actualRows = selectedRows('actual_work_phase')
			if (actualRows.length < 1) {
				return
			}
			if (state.rec.person[0] == null) {
				return
			}
			// err message
			actualRec = actualRows[0]
			if (actualRec.timecard_shift != null) {
				nc.alert(state, state.hdr.capacity.work_phase_timecard_exists_warning || 'Work phase already has a timecard event.')
				return
			}
			shiftRec = rows[0]
			actualRec.timecard_shift = shiftRec.shift_number
			// update showing grid data to make it cange color to grey
			actualNodes = selectedNodes('actual_work_phase')
			actualNode = actualNodes[0]
			actualNode.setData(actualRec)
			// end update showing grid data
			// date = actualRec.prwo_json_data.date // "2017-10-11" #
			rec = {}
			rec.timec_employee_id = state.rec.person[0]
			rec.timec_timecard_state = 'finish' // fix: value from preference
			rec.timec_work_shift = shiftRec.shift_number
			rec.timec_start_time = shiftRec.cap_start_time
			rec.timec_end_time = shiftRec.end_time
			rec.timec_info = shiftRec.info
			// rec.timec_start_time = "2017-10-05 06:00:00"
			// rec.timec_end_time = "2017-10-05 14:00:00"
			// rec.timec_work_time = "7"
			saveData.push(rec)
		} else if (state.rec.state === 'timecard') {
			preferenceName = 'save/local/resource/timecard/save.json'
			saveData = changedRows('timecard')
		} else if (state.rec.state === 'capacity') {
			preferenceName = 'save/local/resource/capacity/save.json'
			saveData = changedRows('capacity')
		} else if (state.rec.state === 'resource_efficiency') {
			preferenceName = 'save/local/resource/resource_efficiency/save.json'
			saveData = changedRows('resource_efficiency')
		}
		nc.callServer(
			state,
			'save',
			{
				save: [{ save_preference: preferenceName, data: saveData }],
				delete: [{ save_preference: preferenceName, data: [loc.gridDataDeleteRec] }]
			},
			() => {
				loc.gridDataDeleteRec = []
				if (state.rec.state !== 'actual') {
					update('update')
				}
			}
		)
	}
}

function filterTimecard(data, take) {
	var ret, tc
	tc = _(state.grid.timecard.data)
		.map(function (rec) {
			return {
				employee_id: rec.timec_employee_id,
				end_date: dt.toDateString(rec.timec_end_time),
				shift: rec.timec_work_shift
			}
		})
		.value()
	ret = _(data)
		.filter(function (rec) {
			var found
			found = _.findIndex(tc, {
				employee_id: rec.prwo_person_id,
				end_date: rec.prwo_json_data.date
			})
			rec.timecard_shift = (found >= 0 && tc[found].shift) || null
			if (take) {
				return found < 0
			}
			return found >= 0
		})
		.value()
	return ret
}

function setData(ret) {
	var grid, key, ref
	// call here capacity_vue_graph_old.coffee graph setData()
	console.debug('form/nc/nc-production', ret)
	if (!(state != null ? state.grid : void 0)) {
		return
	}
	loc.gridDataDeleteRec = []
	loc.gridDataChanged = false
	ref = state.grid
	for (key in ref) {
		grid = ref[key]
		grid.option.callback = gridRowCallback
	}
	if (state.rec.state === 'actual' || state.rec.state === 'checked') {
		state.grid.actual_work_phase.data_orig = state.grid.actual_work_phase.data
		state.grid.actual_work_phase.data = filterTimecard(state.grid.actual_work_phase.data_orig, state.rec.state === 'actual')
	}
}

function filterResource(foreman) {
	var resource
	resource = _(state.popup.resource)
		.filter(function (rec) {
			return foreman.includes(rec.default_foreman_id)
		})
		.map(function (rec) {
			return rec.value
		})
		.value()
	nc.setRec(state, 'resource', resource)
	return resource
}

function filterForeman(resource) {
	var foreman
	foreman = _(state.popup.resource)
		.filter(function (rec) {
			return rec.default_foreman_id !== '' && resource.includes(rec.value)
		})
		.map(function (rec) {
			return rec.default_foreman_id
		})
		.value()
	nc.setRec(state, 'foreman', foreman)
	return foreman
}
function filterPerson(resource) {
	var countString, person, pop, popupPerson
	popupPerson = _(state.popup.person).map(function (rec) {
		return rec.value
	})
	person = _(state.rec.default_capacity)
		.filter(function (rec) {
			var endDt, startDt
			startDt = dt.stringToDate(rec.cap_start_time)
			endDt = dt.stringToDate(rec.cap_end_time)
			// filter only by start date
			return startDt <= state.rec.start_date && endDt >= state.rec.start_date && resource.includes(rec.cap_resource_id) && popupPerson.includes(rec.cap_person_id)
		})
		.map(function (rec) {
			return rec.cap_person_id
		})
		.value()
	loc.selectedPerson = person // warn if same is many times in array = multiple dafault capacities
	pop = _.cloneDeep(state.popup.person)
	if (person.length <= state.rec.max_person_show_count) {
		if (state.popup.person.length > 0 && state.popup.person[0].value.substr(0, 1) === '(') {
			pop.pop() // removes the last element from an array and returns that element
		}
	} else {
		countString = '( ' + person.length + ' )'
		if (pop.length > 0 && pop[pop.length - 1].value.substr(0, 1) === '(') {
			pop[pop.length - 1].value = countString
			pop[pop.length - 1].show = countString
		} else {
			pop.push({
				// adds the last element to an array
				show: countString,
				value: countString
			})
		}
		person = [countString]
	}
	nc.setPopup(state, 'person', pop)
	nc.setRec(state, 'person', person)
	return person
}

function updateJson(action) {
	console.debug('updateJson: ', action)
	if (action === 'to_text') {
		nc.setRec(state, 'capacity_json', nc.toJson(state.rec.capacity))
	} else if (action === 'from_text') {
		nc.setRec(state, 'capacity', nc.fromJson(state.rec.capacity_json))
	}
}

function update(action) {
	var person
	person = loc.selectedPerson
	if (!person || person.length < 1) {
		person = state.rec.person // use manually selected popup value
	}
	if (action === 'update') {
		if (state.rec.state === 'shift') {
			updateJson('to_text')
		} else if (state.rec.state !== 'graph') {
			nc.callServer(
				state,
				'form/nc/nc-production',
				{
					rec: {
						state: state.rec.state,
						start_date: state.rec.start_date,
						end_date: state.rec.end_date,
						person: person,
						resource: state.rec.resource
					}
				},
				setData
			)
		}
	} else if (action === 'start_date') {
		update('update')
	} else if (action === 'end_date') {
		update('update')
	} else if (action === 'foreman') {
		// state.$nextTick -> # wait for popup to update itself
		setTimeout(() => {
			// wait for popup to update itself, should be popup callback
			var resource
			resource = filterResource(state.rec.foreman)
			filterPerson(resource)
		}, 50)
	} else if (action === 'resource') {
		setTimeout(() => {
			// wait for popup to update itself, should be popup callback
			filterForeman(state.rec.resource)
			filterPerson(state.rec.resource)
		}, 50)
	} else if (action === 'person') {
		return
	}
}

// nc.setRec(state, "resource", [])
// nc.setRec(state, "foreman", [])
function tab(newState) {
	state.rec.state = newState
	update('update')
}
