-- -*- mode: lua; coding: windows-1251-dos -*-

local snds = {
	tips_esc_trader_about_anomalies	= [[characters_voice\scenario\trader\trader_tutorial_anomalies_1]],
	gar_dolg_warning				= [[characters_voice\scenario\duty\duty_warning1]],
	esc_return_dv					= [[characters_voice\scenario\trader\return_from_dv]],
	escape_fox_quest				= [[characters_voice\scenario\trader\trader_pda_fox]],
	tip_petruha_report				= [[characters_voice\scenario\escape\petruha_raport_p]],


	tips_agr_krot_sos				= [[characters_voice\scenario\agroprom\krot_help_pda_1]],
	tips_agr_krot_sos1				= [[characters_voice\scenario\agroprom\krot_help_pda_2]],
	tips_agr_krot_sos2				= [[characters_voice\scenario\agroprom\krot_help_pda_2]],
    tips_agr_stalker_help_2			= [[characters_voice\scenario\agroprom\stalker_help_2]],
    tips_agr_stalker_help_1			= [[characters_voice\scenario\agroprom\stalker_help_1]],

    tips_agr_trader_documents		= [[characters_voice\scenario\agroprom\trader_pda_1]],
    pass_to_1st_door                = [[characters_voice\scenario\val\door1_password]],
	pass_to_2nd_door                = [[characters_voice\scenario\val\door2_password]],


	bar_ecolog_crush_heli_down		= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_1]],
	bar_freedom_attack_attract_actor= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_2]],
	bar_freedom_spam_1				= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_6]],
	bar_freedom_spam_2				= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_4]],
	bar_freedom_spam_3				= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_3]],
	bar_freedom_spam_4				= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_5]],
	bar_freedom_attack				= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_7]],
	bar_freedom_attack_spy			= [[characters_voice\scenario\Rostok\Heli_crush\wolfhound_pda_8]],
	bar_ecolog_crush_start_heli		= [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_1]],
	bar_ecolog_crush_attract_actor  = [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_2]],
	bar_ecolog_spam_1				= [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_3]],
	bar_ecolog_spam_2				= [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_4]],
	bar_ecolog_spam_3				= [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_5]],
	bar_ecolog_spam_4				= [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_6]],
	bar_ecolog_attack				= [[characters_voice\scenario\Rostok\Heli_crush\kruglov_pda_7]],
    rostok_kruglov_spam_1			= [[characters_voice\scenario\Rostok\kruglov_pda_help_1]],
    rostok_kruglov_spam_2			= [[characters_voice\scenario\Rostok\kruglov_pda_help_3]],
	bar_ecolog_escape				= [[characters_voice\scenario\Rostok\volkodav_pda_kruglov_escape_1]],
    storyline_vasilyev_tip			= [[characters_voice\scenario\yantar\vasiliev_pda]],
    storyline_ghost_tip 			= [[characters_voice\scenario\yantar\ghost_pda]],
    yan_saharov_message 			= [[characters_voice\scenario\yantar\professor_to_actor_pda_3]],
	yan_saharov_message_2 			= [[characters_voice\scenario\yantar\professor_to_actor_pda_4]],
    yan_saharov_message_3 			= [[characters_voice\scenario\yantar\professor_to_actor_pda_5]],
	
	yan_scientist_probe				= [[characters_voice\scenario\yantar\kruglov_radiation_quest_13]],
	yan_scientist_probe_1			= [[characters_voice\scenario\yantar\kruglov_radiation_quest_11]],
	yan_scientist_probe_2			= [[characters_voice\scenario\yantar\kruglov_radiation_quest_12]],
	yan_scientist_probe_3			= [[characters_voice\scenario\yantar\kruglov_radiation_quest_6]],
	
	rostok_kruglov_follow			= [[characters_voice\scenario\Rostok\pda_kruglov_help_6]],
	bar_freedom_chase				= [[characters_voice\scenario\Rostok\pda_kruglov_stop_enemy_1]],
	rostok_kruglov_follow_2			= [[characters_voice\scenario\Rostok\pda_kruglov_stop_enemy_2]],
	rostok_kruglov_follow_3			= [[characters_voice\scenario\Rostok\pda_kruglov_help_5]],
		
	bar_territory_dolg_1_hit		= [[characters_voice\scenario\bar\pda\voronin_gunfire_pda_1]],
	bar_territory_dolg_2_hit		= [[characters_voice\scenario\bar\pda\voronin_gunfire_pda_2]],
	bar_territory_dolg_3_hit		= [[characters_voice\scenario\bar\pda\voronin_gunfire_pda_3]],
	bar_territory_dolg_kill			= [[characters_voice\scenario\bar\pda\voronin_gunfire_pda_4]],
	
	tips_bun_komand                 = [[characters_voice\scenario\bun\patrol_prikaz]],

	general_ecolog_tip_1            = [[characters_voice\scenario\yantar\professor_to_actor_pda_1]],
    general_ecolog_tip_2            = [[characters_voice\scenario\yantar\professor_to_actor_pda_2]],


    tips_gar_hellcar_alarm			= [[characters_voice\scenario\garbage\neutrals_commander_pda_1]],
	gar_dolg_blokpost_warning		= [[characters_voice\scenario\duty\duty_warning1]],
	gar_dolg_monster_rush			= [[characters_voice\scenario\duty\duty_request1]],
	gar_direction_fire				= [[characters_voice\scenario\garbage\junkyard_combat_ambush]],
	gar_hellcar_victory				= [[characters_voice\scenario\garbage\junkyard_combat_end]],
	gar_actor_looser				= [[characters_voice\scenario\garbage\duty_after_rush_bad]],
	gar_actor_normal				= [[characters_voice\scenario\garbage\duty_after_rush_normal]],
	gar_actor_winner				= [[characters_voice\scenario\garbage\duty_after_rush_good]],


	esc_direction_fire				= [[characters_voice\scenario\escape\lager_fanat_attack]],
	esc_fanat_victory				= [[characters_voice\scenario\escape\lager_fanat_victory]],
	
	rad_barman_spam					= [[characters_voice\scenario\radar\rad_barman_message]],


	val_monolith_trader_pda1		= [[characters_voice\scenario\val\trader_dialog1]],
	o_soznanie_text					= [[characters_voice\scenario\sarcofag\o_soznanie_call]],


-- dublicate pda sounds for remark scheme
    val_rob_leader_jeer_1           = [[characters_voice\scenario\val\rob_leader_jeer_1_p]],

    pri_followers_leader_phrase1_1  = [[characters_voice\scenario\pri\followers_leader_phrase1_1_p]],
    pri_followers_leader_phrase1_2  = [[characters_voice\scenario\pri\followers_leader_phrase1_2_p]],
    pri_followers_leader_phrase1_3  = [[characters_voice\scenario\pri\followers_leader_phrase1_3_p]],
}

local news = {}
local function get_snd(t, k)
	-- log3("getting sound: %s", tostring(k))
	if snds[k] ~= nil then
		return xr_sound.get_safe_sound_object(snds[k])
	else
		return nil
	end
end
local function set_snd(t, k, v)
	--log1("error! we don't do this!")
end
local mt = {}
mt.__index = get_snd
mt.__newindex = set_snd
setmetatable(news, mt)

pda_news = xr_sound.get_safe_sound_object([[device\pda\pda_news]])
pda_tips = xr_sound.get_safe_sound_object([[device\pda\pda_tip]])
pda_task = xr_sound.get_safe_sound_object([[device\pda\pda_objective]])

tips_icons = {
	default  = { 0, 658},
	trader	 = { 332, 893},
	dolg     = { 0, 658},
	freedom  = { 0, 658},
	ecolog   = { 498, 0},
	arena    = { 332, 141},
	stalker  = { 0, 658},
	krot     = { 332, 47},
	barman   = { 332, 235},
	wolf	 = { 332, 940},
	o_soznanie = { 498, 893},
	monolith = { 0, 658},
	saharov  = { 332, 470},
	prizrak  = { 0, 658},
	killer   = { 0, 658},
	maland   = { 415, 752},
	army   = { 415, 517},
	soldier   = { 332, 0},
	anomal   = { 83, 894},
	heli   = { 497, 329},
	mimino   = { 249, 893},
	hue   = { 249, 940},
	info   = { 83, 282},
	bandit   = { 249, 235},
	pillman   = { 498, 422},
	habar   = { 0, 94},
	doll   = { 498, 470},
	ovrah   = { 413, 564},
	artefact   = { 82, 47},
	milstalker   = { 248, 517},
	gravecross   = { 496, 188},
	separ   = { 82, 328},
	dedok   = { 497, 564},
	rat   = { 498, 517}
}

-- Получение иконки отправителя
function get_sender_icon(text, sender)
	if sender == nil or not tips_icons[sender] then
		-- пробуем найти иконку по заголовку СМС
		sender = nil
		
		for k,v in pairs(tips_icons) do
			if (v[3] and string.find(text, v[3], 1, true)) or (v[4] and string.find(text, v[4], 1, true)) then
				sender = k
				break
			end
		end
		
		if sender == nil then
			-- не нашли
			sender = "default"
		end
	end
	
	return tips_icons[sender][1], tips_icons[sender][2]
end


ozvuchka_end = 0

function send_tip(actor, news_id, timeout, sender, showtime, sender_id)
	if news_id == nil then return false end

	if sender_id ~= nil then
		printf("try to send tips for [%s]", tostring(sender_id))
		local sim = alife()
		if sim ~= nil then
			local npc = sim:story_object(sender_id)
			if npc ~= nil then
				if npc.online then
					--в онлайне проверяем на раненность
					if xr_wounded.is_heavy_wounded_by_id(npc.id) then
						printf("[PDA]Cannot send tips [%s], sender is heavy wounded", tostring(news_id))
						return false
					end
				end
				-- в других случаях только на смерть
				if npc:alive() == 1 then
					printf("[PDA]Cannot send tips [%s], sender is dead", tostring(news_id))
					return false
				end
			end
		end
	end

	if timeout == nil then timeout = 0 end
	if showtime == nil then showtime = 5000 end

		--' Играем дефолтный звук
		pda_tips:play_no_feedback(db.actor, sound_object.s2d, timeout, vector():set( 0, 0, 0 ), 1.0)
	--	pda_tips:play(db.actor, timeout, sound_object.s2d)
		local news_snd = news[news_id]
		if news_snd ~= nil then
			--' Играем звук забитый
			news_snd:play(db.actor, timeout+1, sound_object.s2d)

			--' Необходимо поставить время показа по длине сцены
			local length = news_snd:length()
		if length > showtime then
			showtime = length
		end
	end
	
	if sender == nil then
		sender = "default"
	end
	local news_text = game.translate_string(news_id)
	local x,y = get_sender_icon(news_text, sender)	
	actor:give_game_news(news_text, "ui\\ui_iconsTotal", Frect():set(x,y,83,47), timeout*1000, showtime)
	return true
end

function send_tip_nosound(actor, news_id, timeout, sender)
	if news_id == nil then return end

	timeout = 0

	--' Играем дефолтный звук
	pda_tips:play(db.actor, timeout, sound_object.s2d)
	local news_sound = news[news_id]

	return news_sound
end

local action_descr_by_type = {
	new = "general_new_task",
	update = "general_update_task",
	complete = "general_complete_task",
	fail = "general_fail_task"
}

local cycle_task = {
	"eliminate_lager",
	"defend_lager",
	"kill_stalker",
	"artefact",
	"monster_part",
	"find_item"
}


local autosave_t
skip_send_task = false

function send_task(actor, type, task, objective)
	-- u3_utils.printf("send_task function started with type: "..type..".")
	if db.actor == nil then return false end
	if skip_send_task then return end
	
	local task_title = task:get_title()
	local task_time = string.find(task_title, "\\n", 1, true)
	if task_time then
		task_title = string.sub(task_title, 1, task_time-1)
	end
	local skip_autosave = false -- пропуск циклических заданий
	local news_text, task_texture, task_rect
	local objective_index = objective:get_idx() + 1
        
	--' Играем дефолтный звук
	pda_task:play(db.actor, 0, sound_object.s2d)

	-- цвет сообщения
	local text_color = "%c[default]"
	if type == "fail" then
		text_color = "%c[255,255,0,0]"
	end
	if type == "complete" then
		text_color = "%c[255,0,255,0]"
	end
	if type == "update" then
		text_color = "%c[255,0,255,255]"
	end
	if type == "new" then
		text_color = "%c[255,0,255,255]"
	end
	
	-- циклическое ли задание?
	local cycle_task_type = nil
	for i,task_type in ipairs(cycle_task) do
		if task_title == game.translate_string(task_type) then
			cycle_task_type = i
			break
		end
	end
	
	if cycle_task_type then
		skip_autosave = true
		
		--' Циклическое задание - берем координаты из текстуры таска
		task_texture, task_rect = get_texture_info("ui_iconsTotal_"..cycle_task[cycle_task_type], "ui_iconsTotal_locations")
		
		news_text = text_color..game.translate_string(action_descr_by_type[type]).."\\n"..game.translate_string(task_title)..": "..game.translate_string(task:get_objective(1):get_description())
	else
		--' Берем координаты единой текстуры
		task_texture, task_rect = get_texture_info("ui_iconsTotal_locations", "ui_iconsTotal_locations")
		
		news_text = text_color..game.translate_string(action_descr_by_type[type]).."\\n"..game.translate_string(task_title)
		
		if type ~= "complete" and type ~= "fail" then
			-- workaround for incomplete objective list
			if task:get_objectives_cnt() == objective_index then
				objective_index = objective_index - 1
			end
			
			if type == "new" then
				local obj_desc = task:get_objective(objective_index):get_description()
				if obj_desc ~= nil then
					news_text = news_text..": "..text_color..game.translate_string(obj_desc)
				end
			elseif type == "update" then
				local obj_desc1 = task:get_objective(objective_index-1):get_description()
				local obj_desc2 = task:get_objective(objective_index):get_description()
				if obj_desc1 ~= nil then
					news_text = news_text.."\\n"..text_color.."Завершено: "..game.translate_string(obj_desc1)
				end
				if obj_desc2 ~= nil then
					news_text = news_text.."\\n"..text_color.."Следующее: "..game.translate_string(obj_desc2)
				end
			end
		end
		
	end

	if db.actor:is_talking() then	
		db.actor:give_talk_message(news_text, task_texture, task_rect,"iconed_answer_item")
	end	
	--выдаем в любом случае чтобы попало в дневник
	db.actor:give_game_news(news_text, task_texture, task_rect, 0, 5000)
	
	if type == "new" or
		type == "update"
	then
		--' Выдать новое подзадание
		if task:get_objectives_cnt() == objective_index then
			return
		end
		news_text = game.translate_string(task:get_objective(objective_index):get_description())
	else
		news_text = text_color..game.translate_string(task_title).." - "..game.translate_string(action_descr_by_type[type])
	end

	-- автосохранение только при получении и сдаче задания. циклические
	-- задания игнорируются.
	if not skip_autosave then
	  local news_text_save = game.translate_string( task_title )
	  if type == "complete" then
	    news_text_save = news_text_save.." - завершено"
	  end
	  -- удаляем предыдущий таймер на сохранение при сдаче/получении
	  -- нескольких квестов в одном диалоге 
	  -- сохраняем только самый последний автосейв по завершении диалога
	  if type == "new" or type == "complete" then
	    if autosave_t then autosave_t:stop() end
	    autosave_t = dsh.timeout( 3000, function()
	      autosave( news_text_save )
	    end )
	  end
	end

	local hud = get_hud()
	hud:AddCustomStatic("main_task", true)
	hud:GetCustomStatic("main_task"):wnd():SetTextST(news_text)
	hud:GetCustomStatic("main_task").m_endTime = time_global()/1000 + 10
end


function autosave( text )
  if u3_utils.can_save() then
    autosave_t = nil
    u3_utils.savegame( text )
  else
    autosave_t = dsh.timeout( 3000, function()
      autosave( text )
    end )
  end
end


function send_encyclopedy(type, title)
	if type == "Diary" then
			pda_news:play(db.actor, 0, sound_object.s2d)


		--' Берем координаты из текстуры таска
		local task_texture, task_rect = get_texture_info("ui_iconsTotal_locations", "ui_iconsTotal_locations")
		local news_text = "%c[255,160,160,160]"..game.translate_string("st_found_new_pda").."\\n".."%c[default]"..game.translate_string(title)
		if db.actor:is_talking() then	
			db.actor:give_talk_message(news_text, task_texture, task_rect,"iconed_answer_item")
		else
			db.actor:give_game_news(news_text, task_texture, task_rect, 0, 3000)
		end	
	end
end

function send_treasure(name)
	local 	level_name = {
		["esc"]  = "Кордон",
		["gar"]  = "Свалка",
		["agr"]  = "Агропром",
		["agr_u"] = "Подземелье Агропрома",
		["val"]  = "Тёмная Долина",
		["mil"]  = "Армейские Склады",
		["yan"]  = "Янтарь",
		["x16"]  = "Лаборатория Х-16",
		["rad"]  = "Радар",
		["pri"]  = "Припять",
		["x18"]  = "Лаборатория Х-18",
		["bar"]  = "Бар",
		["ros"]  = "Дикая Территория"
	}
	pda_news:play(db.actor, 0, sound_object.s2d)
	local task_texture, task_rect = get_texture_info("ui_iconsTotal_found_thing")
	local level_key = string.sub(name,1,string.find(name,"_s",1,plain)-1)
	local tmp_str = ""
	if level_name[level_key] ~= nil then
		tmp_str = level_name[level_key]..": "
	end
	local news_text = "%c[255,160,160,160]"..game.translate_string("st_found_new_treasure").."\\n".."%c[120,255,120,160]"..tmp_str.."%c[170,200,200,200]"..game.translate_string(name)	
	db.actor:give_game_news(news_text, task_texture, task_rect, 0, 10000)
end


function get_inv_name( section )
  return get_string( section, "inv_name" )
end


function __relocate_item( actor, type, item, num )
  if db.actor == nil then return false end
  local item_name = game.translate_string( get_inv_name( item ) )
  if ( num or 1 ) > 1 then
    item_name = num .. "x " .. item_name
  end
  -- Играем дефолтный звук
  if type == "in" then
    local task_texture, task_rect = get_texture_info(
      "ui_iconsTotal_found_thing"
    )
    local news_text = "%c[255,105,239,146]"
      .. game.translate_string( "general_in_item" ) .. "\\n"
      .. "%c[default]" .. item_name
    if db.actor:is_talking() then
      db.actor:give_talk_message(
        news_text, task_texture, task_rect, "iconed_answer_item"
      )
    else
      db.actor:give_game_news( news_text, task_texture, task_rect, 0, 2000 )
    end		
  elseif type == "out" then
      local task_texture, task_rect = get_texture_info(
        "ui_iconsTotal_lost_thing"
      )
    local news_text = "%c[255,255,085,085]"
      .. game.translate_string( "general_out_item" ) .. "\\n"
      .. "%c[default]" .. item_name
    if db.actor:is_talking() then
      db.actor:give_talk_message(
        news_text, task_texture, task_rect, "iconed_answer_item"
      )
    else
      db.actor:give_game_news( news_text, task_texture, task_rect, 0, 2000 )
    end		
  end
end


function relocate_item( actor, type, item, num )
  --return __relocate_item( actor, type, item, num )
  return relocate_item_ex( type, item, num )
end


function get_talk_item_icon( sect )
  local icon = CIconParams( sect )
  local texture, rect
  if icon.icon_name then
    texture, rect = get_texture_info( icon.icon_name )
  else
    texture = dsh.get_ui_icon_equipment_name( sect )
    rect    = icon:original_rect()
    rect.x2 = rect.x2 - rect.x1
    rect.y2 = rect.y2 - rect.y1
  end
  return {
    texture, rect,
    ( "ico_item_" .. icon.grid_width .. "_" .. icon.grid_height )
  }
end


function relocate_item_ex( type, item, num, news_text )
  local item_name = game.translate_string( get_inv_name( item ) )
  if ( num or 1 ) > 1 then
    item_name = num .. "x " .. item_name
  end
  -- Играем дефолтный звук
  if type == "in" then
    if not news_text then
      news_text = "%c[255,105,239,146]"
        .. game.translate_string( "general_in_item" )
        .. "%c[default] " .. item_name
    end
    if db.actor:is_talking() then
      db.actor:give_talk_message(
        news_text, unpack( get_talk_item_icon( item ) )
      )
    else
      local task_texture, task_rect = get_texture_info(
        "ui_iconsTotal_found_thing"
      )
      db.actor:give_game_news( news_text, task_texture, task_rect, 0, 2000 )
    end		
  elseif type == "out" then
    if not news_text then
      news_text = "%c[255,255,085,085]"
        .. game.translate_string( "general_out_item" )
        .. "%c[default] " .. item_name
    end
    if db.actor:is_talking() then
      db.actor:give_talk_message(
        news_text, unpack( get_talk_item_icon( item ) )
      )
    else
      local task_texture, task_rect = get_texture_info(
        "ui_iconsTotal_lost_thing"
      )
      db.actor:give_game_news( news_text, task_texture, task_rect, 0, 2000 )
    end		
  end
end


function relocate_money(actor, type, amount)
	if db.actor == nil then return false end


	--' Играем дефолтный звук
	if type == "in" then
		local task_texture, task_rect = get_texture_info("ui_iconsTotal_found_money")
		local news_text = "%c[255,105,239,146]"..game.translate_string("general_in_money").."\\n".."%c[default]"..game.translate_string(tostring(amount))
		
		if db.actor:is_talking() then
			db.actor:give_talk_message(news_text, task_texture, task_rect, "iconed_answer_item")
		else
			db.actor:give_game_news(news_text, task_texture, task_rect, 0, 2000)
		end		
	elseif type == "out" then
		local task_texture, task_rect = get_texture_info("ui_iconsTotal_lost_money")
		local news_text = "%c[255,255,085,085]"..game.translate_string("general_out_money").."\\n".."%c[default]"..game.translate_string(tostring(amount))
		
		if db.actor:is_talking() then
			db.actor:give_talk_message(news_text, task_texture, task_rect, "iconed_answer_item")
		else
			db.actor:give_game_news(news_text, task_texture, task_rect, 0, 2000)
		end		
	end
end
