local LrDialogs = import 'LrDialogs'
local LrHttp = import 'LrHttp'
local LrPrefs = import 'LrPrefs'
local LrTasks = import 'LrTasks'
local LrView = import 'LrView'

local Detect = require 'Detect'
local Diagnostics = require 'Diagnostics'
local FILM_TYPES = require 'FilmTypes'
local License = require 'License'

local LABELS = {
	{ title = 'Red', value = 'red' },
	{ title = 'Yellow', value = 'yellow' },
	{ title = 'Green', value = 'green' },
	{ title = 'Blue', value = 'blue' },
	{ title = 'Purple', value = 'purple' },
	{ title = 'None', value = 'none' },
}

return {
	sectionsForTopOfDialog = function(f, _)
		local prefs = LrPrefs.prefsForPlugin()
		local bind = LrView.bind

		-- Detect.run() ignores pythonPath entirely once a bundled engine is
		-- present (see Detect.lua); say so here too, or the always-populated
		-- pythonPath field reads as a requirement it isn't.
		local engine = Detect.enginePath()

		local function labeledNumber(title, key, tooltip)
			return f:row {
				f:static_text { title = title, width = LrView.share 'cc_label' },
				f:edit_field {
					value = bind(key),
					width_in_chars = 7,
					tooltip = tooltip,
				},
			}
		end

		return {
			{
				title = 'Cut Corners: License',
				bind_to_object = prefs,

				f:row {
					f:static_text { title = License.statusText() },
				},
				f:row {
					f:static_text { title = 'License key:', width = LrView.share 'cc_label' },
					f:edit_field {
						value = bind 'licenseKey',
						width_in_chars = 24,
						immediate = true,
					},
					f:push_button {
						title = 'Verify',
						action = function()
							if License.isLicensed() then
								LrDialogs.message('Cut Corners',
									'License key verified - thank you for'
										.. ' supporting Cut Corners.')
							else
								LrDialogs.message('Cut Corners',
									'That key did not verify. Check it for typos'
										.. ' (keys look like CC-XXXXX-XXXXX-XXXXX),'
										.. ' or contact support@cutcorners.app.')
							end
						end,
					},
					f:push_button {
						title = 'Buy a license...',
						action = function()
							LrHttp.openUrlInBrowser(License.BUY_URL)
						end,
					},
				},
			},
			{
				title = 'Cut Corners',
				bind_to_object = prefs,

				engine
					and f:row {
						f:static_text { title = 'Detector:', width = LrView.share 'cc_label' },
						f:static_text { title = 'Bundled engine — Python is not required' },
					}
					or f:row {
						f:static_text { title = 'Python executable:', width = LrView.share 'cc_label' },
						f:edit_field { value = bind 'pythonPath', width_in_chars = 35 },
					},
				engine
					and f:row {
						f:static_text {
							title = 'Detector: bundled engine at ' .. engine,
							font = '<system/small>',
						},
					}
					or f:row {
						f:static_text {
							title = 'Needs Python 3 with: pip install opencv-python numpy',
							font = '<system/small>',
						},
					},
				f:row {
					f:static_text { title = 'Default film type:', width = LrView.share 'cc_label' },
					f:popup_menu { items = FILM_TYPES, value = bind 'filmType' },
				},
				f:row {
					f:static_text { title = 'Label for skipped:', width = LrView.share 'cc_label' },
					f:popup_menu { items = LABELS, value = bind 'skipLabel' },
				},
				labeledNumber('Edge band:', 'edgeBand',
					'Corners must lie within this fraction of each edge (default 0.10)'),
				labeledNumber('Crop inset:', 'inset',
					'Shrink the detected frame by this fraction to exclude the rebate edge (default 0.005)'),
				labeledNumber('Keep border:', 'border',
					'Margin of rebate kept outside the detected frame, as a fraction of its short side; 0 = off (default). When set, crop inset is ignored'),
				labeledNumber('Aspect target:', 'aspectTarget',
					'Long/short side target; 1.5 for 35mm full frame'),
				labeledNumber('Aspect tolerance:', 'aspectTolerance',
					'Relative tolerance before a frame is flagged (default 0.08)'),
				labeledNumber('Min frame area:', 'minArea',
					'Smallest accepted frame as a fraction of the film area, excluding scanner background (default 0.64)'),
				labeledNumber('Max frame area:', 'maxArea',
					'Largest accepted frame as a fraction of the whole scan (default 0.99)'),
				labeledNumber('Manual threshold:', 'manualThreshold',
					'Fixed brightness cutoff 1-255 replacing the adaptive threshold; 0 = adaptive (default). Ignored in auto-detect mode'),
				labeledNumber('Max preview size:', 'maxPixels',
					'Longest edge of the exported detection previews in pixels (default 1500; larger is more precise but slower)'),
				f:row {
					f:static_text { title = '', width = LrView.share 'cc_label' },
					f:checkbox {
						title = 'Mask dark film holder edges',
						value = bind 'darkEdgeMask',
						tooltip = 'Treat dark scan surround (film holder / carrier) as background, not film',
					},
				},
				f:row {
					f:static_text { title = '', width = LrView.share 'cc_label' },
					f:checkbox {
						title = 'Enforce aspect ratio',
						value = bind 'enforceAspect',
						tooltip = 'When one crop edge sits on a bright streak in the rebate (light past a slide mount aperture, halation, stock printing) instead of the frame, use the aspect target to find the real film edge and move it there',
					},
				},
			},
			{
				title = 'Cut Corners: Support',
				bind_to_object = prefs,

				f:row {
					f:push_button {
						title = 'Run Diagnostics',
						action = function()
							LrTasks.startAsyncTask(function()
								LrDialogs.message('Cut Corners diagnostics',
									Diagnostics.report())
							end)
						end,
					},
					f:push_button {
						title = 'Open the usage guide...',
						action = function()
							LrHttp.openUrlInBrowser('https://cutcorners.app/guide')
						end,
					},
				},
				f:row {
					f:checkbox {
						title = 'Write a log file for support (takes effect after reloading the plugin)',
						value = bind 'enableLogging',
					},
				},
				f:row {
					f:static_text {
						title = 'Support: support@cutcorners.app - include the diagnostics output and, for detection issues, a "Save diagnostic images" run.',
						font = '<system/small>',
						width = 480,
						height_in_lines = 2,
					},
				},
			},
		}
	end,
}
