dofile(LockOn_Options.script_path .. "devices.lua")
dofile(LockOn_Options.script_path .. "command_defs.lua")
dofile(LockOn_Options.script_path .. "utils.lua")
dofile(LockOn_Options.script_path .. "sensors/rwrSymbols.lua")
dofile(LockOn_Options.script_path .. "Systems/electric_system_api.lua")
local gettext = require("i_18n")
_ = gettext.translate

dofile [[Scripts\socket.lua]]
local gettime = socket.gettime

local firstRun = false

local Sensor_Data_Raw = get_base_data()

local head_az = get_param_handle('HEAD_AZ')
local head_el = get_param_handle('HEAD_EL')

-- rwr_brightness = get_param_handle(Nav_Radar_brightness_parameter)

local update_time_step = 0.05
make_default_activity(update_time_step)
new_contact_time = 7.5
local rwrSystem = GetSelf()

local rwrVol = 0.5

MaxThreats = 20
EmitterLiveTime = 1.85--7.0
EmitterSoundTime = 0.5
LaunchSoundDelay = 15.0

DefaultType = 100

RWR_detection_coeff = 0.85
DEFAULT_TYPE_ = { DefaultType, DefaultType, DefaultType, DefaultType }

eyes = {} -- sensor locations
eyes[1] = {
    position = {
        x = 2.57,
        y = -0.7,
        z = 0.8
    }, -- {Forward/Back,U/D,L/R}
    orientation = {
        azimuth = math.rad(45),
        elevation = math.rad(0.0)
    },
    field_of_view = math.rad(120)
}
eyes[2] = {
    position = {
        x = 2.57,
        y = -0.7,
        z = -0.8
    },
    orientation = {
        azimuth = math.rad(-45),
        elevation = math.rad(0.0)
    },
    field_of_view = math.rad(120)
}
eyes[3] = {
    position = {
        x = -3,
        y = 0.5,
        z = 0.3
    },
    orientation = {
        azimuth = math.rad(135),
        elevation = math.rad(0.0)
    },
    field_of_view = math.rad(120)
}
eyes[4] = {
    position = {
        x = -3,
        y = 0.5,
        z = -0.3
    },
    orientation = {
        azimuth = math.rad(-135),
        elevation = math.rad(0.0)
    },
    field_of_view = math.rad(120)
}

---------------------------------------------------------------------------------

rwr = {}
for ia = 1, 20 do
    local i
    if ia < 10 then
        i = "_0" .. ia .. "_"
    else
        i = "_" .. ia .. "_"
    end
    rwr[ia] = {
        elevation_h = get_param_handle("RWR_CONTACT" .. i .. "ELEVATION"),
        azimuth_h = get_param_handle("RWR_CONTACT" .. i .. "AZIMUTH"),
        power_h = get_param_handle("RWR_CONTACT" .. i .. "POWER"),
        unit_type_h = get_param_handle("RWR_CONTACT" .. i .. "UNIT_TYPE"),

        general_type_h = get_param_handle("RWR_CONTACT" .. i .. "GENERAL_TYPE"),
        priority_h = get_param_handle("RWR_CONTACT" .. i .. "PRIORITY"),
        signal_h = get_param_handle("RWR_CONTACT" .. i .. "SIGNAL"),
        time_h = get_param_handle("RWR_CONTACT" .. i .. "TIME"),
        source_h = get_param_handle("RWR_CONTACT" .. i .. "SOURCE"),

        unit_type_sym_h = get_param_handle("RWR_CONTACT" .. i .. "UNIT_TYPE_SYM"),
        unit_type_sym_num = get_param_handle("RWR_CONTACT" .. i .. "UNIT_TYPE_SYM_NUMERIC"),

        unit_type_is_num = get_param_handle("RWR_CONTACT" .. i .. "UNIT_TYPE_IS_NUMERIC"),
        power_sym_h = get_param_handle("RWR_CONTACT" .. i .. "POWER_SYM"),
        color_sym_h = get_param_handle("RWR_CONTACT" .. i .. "COLOR"),
        first_seen = get_param_handle("RWR_CONTACT" .. i .. "FIRST_SEEN"),
        scan_sym = get_param_handle("RWR_CONTACT" .. i .. "SCAN_SYM"),
    }
    rwr[ia].first_seen:set(-1.0)
end
---------------------------------------------------------------------------------
local hmd_rwr = {}
--for i = 1, MaxThreats do
--    hmd_rwr[i] = {
--        x = get_param_handle(string.format("HMD_RWR_%02d_X", i)),
--        y = get_param_handle(string.format("HMD_RWR_%02d_Y", i)),
--    }
--end
--------------------------------------------------------------------------------
-- 独立函数：为 RWR 目标计算 HMD 坐标
--------------------------------------------------------------------------------
local function update_rwr_hmd()
    -- 1) 读取机身姿态（Roll/Pitch, 弧度）
    -- RWR读数始终基于机体系，无需考虑机体补偿

    -- 2) 读取头盔偏移（度→弧度）
	local head_az_deg = head_az:get() or 0
    local head_el_deg = head_el:get() or 0
    local head_az_rad = math.rad(head_az_deg)
    local head_el_rad = math.rad(head_el_deg)

    -- 3) 对每个 RWR 目标做四元数补偿并写入 HMD 平面坐标
    for i = 1, MaxThreats do
		local r=rwr[i]
		local h=hmd_rwr[i]
		if r.signal_h~=0 then
			h = {
				x = get_param_handle(string.format("HMD_RWR_%02d_X", i)),
				y = get_param_handle(string.format("HMD_RWR_%02d_Y", i)),
				behind=get_param_handle(string.format("HMD_RWR_%02d_BEHIND", i))
			}
			local az = -r.azimuth_h:get()
			local el = r.elevation_h:get()

			-- 球坐标→向量
			local v = {
				math.cos(el) * math.cos(az),
				math.cos(el) * math.sin(az),
				math.sin(el)
			}

			-- 构造补偿四元数（去除机身滚转和俯仰）
			--local q_body = Quat_from_euler(roll, pitch, 0)			
			local q_head = Quat_from_euler(0, head_el_rad, head_az_rad)
			-- 四元数旋转
			--local v_body = Rotate_vector_by_quaternion(v, q_body)
			local v_hmd = Rotate_vector_by_quaternion(v,q_head)
			-- 基于头盔向量的后半球判断
			if v_hmd[1] > 0 then
				h.behind:set(0)
			else
				-- 后半球标记
				h.behind:set(1)
			end
			-- 向量→补偿后角度
			--local comp_az, comp_el = Vector_to_angles(v)
			--comp_el = el
			-- 叠加头盔朝向
			local final_az = az + head_az_rad
			local final_el = el - head_el_rad

			local x = math.tan(final_az)
			local y = math.tan(final_el)
			-- 投影写句柄
			h.x:set(x)
			h.y:set(y)

		end
    end
end

function round(num, idp)
    local mult = 10 ^ (idp or 0)
    return math.floor(num * mult + 0.5) / mult
end

function post_initialize()
    sndhost = create_sound_host("COCKPIT_RADAR_WARN", "HEADPHONES", 0, 0, 0)
    rwrLaunch = sndhost:create_sound("Aircrafts/Cockpits/RWR/Launch")--rwrLaunch = sndhost:create_sound("Cockpit/rwr_warn")
    rwrLock = sndhost:create_sound("Aircrafts/Cockpits/RWR/LockWarning")--rwrLock = sndhost:create_sound("Cockpit/rwr_lock")
    initRwr = sndhost:create_sound("Aircrafts/J-20A/Cockpit/rwr/init")
    local birth = LockOn_Options.init_conditions.birth_place
    if birth == "GROUND_HOT" or birth == "AIR_HOT" then
        firstRun = true
    elseif birth == "GROUND_COLD" then

    end
end

function SetCommand(command, value)
    if command == click_cmd.RWR_Volume then
        rwrVol = 0.5*value
    end
end
local function update_rwr_volume()
    local new_val = (rwrVol + 1.0) / 2.0
    local volumeLock = math.pow((((round(new_val / 0.5, 2)) * 0.3)), 3)
    local volumeWarn = math.pow((((round(new_val / 0.5, 2)) * 0.4)), 3)
    rwrLock:update(nil, volumeLock, nil)
    rwrLaunch:update(nil, volumeWarn, nil)
end
local counter = 0

function update()
    -- print_message_to_user(rwrOverlay:get())
    if get_elec_primary_ac_ok() then
        update_rwr_volume()
    end
    if counter > 1 then
        counter = 0
    else
        counter = counter + update_time_step
    end


    local tmp_type, tmp_signal, tmp_gen_type
    local lock = false
    local warn = false
    for i = 1, 20 do

        tmp_type = rwr[i].unit_type_h:get()

        tmp_gen_type = rwr[i].general_type_h:get()
        if tmp_type and tmp_type ~= "" then

            if tmp_type ~= 0 then
                if rwr[i].time_h:get() == -1 then
                    rwr[i].first_seen:set(-1)
                else
                    if rwr[i].first_seen:get() == -1 then
                        rwr[i].first_seen:set(gettime())
                    end
                end

                tmp_signal = rwr[i].signal_h:get()

                if tmp_signal == 2 then -- 2 Lock
                    lock = true
                    rwr[i].color_sym_h:set(1.0)
					rwr[i].scan_sym:set(0.8)
                elseif tmp_signal == 3 then -- 3 Launch
                    warn = true
                    lock = true
                    rwr[i].color_sym_h:set(2.0)
					rwr[i].scan_sym:set(0.5)
                else -- else 1 - Search
                    rwr[i].color_sym_h:set(3.0)
					rwr[i].scan_sym:set(1.0)
                end

                symb = symbols[tmp_type]
                if symb == nil then
                    symb = "UU"
                end
                if tonumber(symb) ~= nil then
                    rwr[i].unit_type_sym_num:set(symb)
                    if tmp_signal == 3 then
                        if math.floor(counter*10 % 2) == 0 then
                            rwr[i].unit_type_is_num:set(1.0)
                        else
                            rwr[i].unit_type_is_num:set(0)
                        end
                    else
                        rwr[i].unit_type_is_num:set(1.0)
                    end
                else
                    rwr[i].unit_type_sym_h:set(symb)
                    if tmp_signal == 3 then
                        if math.floor(counter*10 % 2) == 0 then
                            rwr[i].unit_type_is_num:set(0.5)
                        else
                            rwr[i].unit_type_is_num:set(0)
                        end
                    else
                        rwr[i].unit_type_is_num:set(0.5)
                    end
                end
            end
        end
        tmp = 1 - rwr[i].power_h:get() + 0.1
        rwr[i].power_sym_h:set(tmp)
    end

	update_rwr_hmd()

    if get_elec_primary_ac_ok() then
        if lock == false then
            if rwrLock:is_playing() then
                rwrLock:stop()
            end
        else

            if not rwrLock:is_playing() then
                rwrLock:play_continue()
            end
        end

        if warn == false then
            if rwrLaunch:is_playing() then
                rwrLaunch:stop()
            end
        else
            if not rwrLaunch:is_playing() then
                rwrLaunch:play_continue()
            end
        end
    else
        if rwrLock:is_playing() then
            rwrLock:stop()
        end
        if rwrLaunch:is_playing() then
            rwrLaunch:stop()
        end
    end

    if get_elec_primary_ac_ok() then
        if not firstRun then
            initRwr:play_once()
            firstRun = true
        end
        rwrSystem:set_power(true)
    else
        rwrSystem:set_power(false)
    end

end

need_to_be_closed = false --不关闭该lua