download_campaign = {}

download_campaign.options = s4.g_GameOptions.Instance().GetDownloadOptions()
	
download_campaign.strings = {}
download_campaign.strings[0] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$559"))

download_campaign.enum = {}

download_campaign.enum.pay = 0
download_campaign.enum.free = 1

download_campaign.enum.old = 0
download_campaign.enum.new = 1
download_campaign.enum.updated = 2

download_campaign.tables = {}
download_campaign.tables[download_campaign.enum.pay] = _T("table_pay_campaigns")
download_campaign.tables[download_campaign.enum.free] = _T("table_free_campaigns")

download_campaign.state_images = {}
download_campaign.state_images[download_campaign.enum.new] = _T("gui_controls_pic_new")
download_campaign.state_images[download_campaign.enum.updated] = _T("gui_controls_pic_update")
download_campaign.state_images[download_campaign.enum.old] = _T("")

download_campaign.titles = {}
download_campaign.titles[0] = _T("¹")
download_campaign.titles[1] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$515"))
download_campaign.titles[2] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$516"))
download_campaign.titles[3] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$517"))
download_campaign.titles[4] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$518"))
download_campaign.titles[5] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$519"))

download_campaign.button_captions = {}
download_campaign.button_captions[download_campaign.enum.pay] = {}
download_campaign.button_captions[download_campaign.enum.free] = {}
download_campaign.button_captions[download_campaign.enum.pay][download_campaign.enum.old] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$511"))
download_campaign.button_captions[download_campaign.enum.pay][download_campaign.enum.new] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$511"))
download_campaign.button_captions[download_campaign.enum.pay][download_campaign.enum.updated] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$512"))
download_campaign.button_captions[download_campaign.enum.free][download_campaign.enum.old] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$513"))
download_campaign.button_captions[download_campaign.enum.free][download_campaign.enum.new] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$513"))
download_campaign.button_captions[download_campaign.enum.free][download_campaign.enum.updated] = sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$512"))

download_campaign.url_campaigns = download.app.GetSettings().GetChild(_T("settings"), false).GetValue(_T("url_new_campaigns"))

download_campaign.window = {}
download_campaign.campaigns = {}

download_campaign.thread_proc_params = {}
download_campaign.campaign_name = _T("")

download_campaign.func_prepare_download_campaign = function (_owner)

	local label_text = __cast(_owner.GetWidget(_T("label_text")), sf.gui.CLabelWidget)
	local text = std.wstring(label_text.GetText())
	label_text.SetText(_T(string.format(T_(text).c_str(), T_(download_campaign.campaign_name).c_str())))

end

download_campaign.func_prepare_download_campaign_cancel = function (_owner)

	local label_text = __cast(_owner.GetWidget(_T("label_text")), sf.gui.CLabelWidget)
	local text = std.wstring(label_text.GetText())
	label_text.SetText(_T(string.format(T_(text).c_str(), T_(download_campaign.campaign_name).c_str())))

end

download_campaign.sort_func = {}

download_campaign.sort_func[0] = 	
	function (_camp1, _camp2) 
		if _camp1.Name == _camp2.Name then
			return (game.get_lua_time(_camp1.LastUpdate) > game.get_lua_time(_camp2.LastUpdate))
		else
			return sf.misc.StringCompare(_camp1.Name, _camp2.Name)
		end
	end 

download_campaign.sort_func[1] = 
	function (_camp1, _camp2) 
		return (game.get_lua_time(_camp1.LastUpdate) > game.get_lua_time(_camp2.LastUpdate))
	end 

download_campaign.sort_func[2] = 
	function (_camp1 , _camp2) 
		return (_camp1.LevelCount > _camp2.LevelCount)
	end

download_campaign.sort_func[3] = 	
	function (_camp1, _camp2) 
		if _camp1.Author == _camp2.Author then
			return (game.get_lua_time(_camp1.LastUpdate) > game.get_lua_time(_camp2.LastUpdate))
		else
			return sf.misc.StringCompare(_camp1.Author, _camp2.Author)
		end
	end 

download_campaign.sort_func[4] = 
	function (_camp1, _camp2) 
		return (_camp1.AverRating > _camp2.AverRating)
	end 

download_campaign.fill_table = function(_owner, _tc)
		
	download_campaign.campaigns[_tc].table.ClearTable()

	local template = download.app.GetSettings().GetChild(_T("GUITemplates"), false)

	download_campaign.campaigns[_tc].table.LoadRow(download_campaign.campaigns[_tc].rowinfo, template)
	
	for column_i=0, 5 do
		local label = __cast(download_campaign.campaigns[_tc].table.GetCell(0, column_i).GetWidget(_T("label")), sf.gui.CLabelWidget)
		label.SetText(download_campaign.titles[column_i])
		download_campaign.campaigns[_tc].table.GetCell(0, column_i).UpdateLayout()
	end

	local info = download_campaign.campaigns[_tc].rowinfo.GetNextSibling()

	for i=1, download_campaign.campaigns[_tc].count do
			
		local strings = {}
		strings[0] = _T(tostring(i))
		strings[1] = download_campaign.campaigns[_tc].items[i].Name
		strings[2] = _T(os.date("%x", game.get_lua_time(download_campaign.campaigns[_tc].items[i].LastUpdate)))
		strings[3] = _T(tostring(download_campaign.campaigns[_tc].items[i].LevelCount))
		strings[4] = download_campaign.campaigns[_tc].items[i].Author
	
		download_campaign.campaigns[_tc].table.LoadRow(info, template)
		
		local cs = download_campaign.campaigns[_tc].table.GetCellsCount()
		
		local image = sf.graphics.CImage(download_campaign.state_images[download_campaign.campaigns[_tc].items[cs.Y-1].State])
		download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, 1).GetWidget(_T("pic_state")).get().SetSize(
			image.GetTextureSize().X, image.GetTextureSize().Y)
		local pic_state = __cast(download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, 1).GetWidget(_T("pic_state")), sf.gui.CImageWidget)
		pic_state.SetImage(image)
			
		download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, 1).GetWidget(_T("pic_state")).get().UpdateLayout()
		
		for column_i=0, 4 do
			local label = __cast(download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, column_i).GetWidget(_T("label")), sf.gui.CLabelWidget)
			label.SetText(strings[column_i]);
			label.ResizeToFitText(false);
			download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, column_i).UpdateLayout()
		end
		
		local slider_rating = __cast(download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, 5).GetWidget(_T("rating")), s4.CFixedSliderWidget)
		local rating = download_campaign.campaigns[_tc].items[i].AverRating
		if rating == -1 then rating=5 end
		slider_rating.SetValue(2*rating, false)
		download_campaign.campaigns[_tc].table.GetCell(cs.Y-1, 5).UpdateLayout()
		
	end
	
	download_campaign.campaigns[_tc].table.FitCells();
	
	if download_campaign.campaigns[_tc].table.GetCellsCount().Y>1 then
		download_campaign.campaigns[_tc].table.SelectRow(1)
	end
end	
	
download_campaign.update_button_caption = function(_owner, _tc)
	
	download_campaign.window.label_description.SetText(_T(""))
	
	local num_campaign = download_campaign.campaigns[_tc].table.GetSelectedRow()
		
	if num_campaign==-1 or num_campaign > download_campaign.campaigns[_tc].count or  download_campaign.campaigns[_tc].count == 0 then return end
	
	download_campaign.window.button_buy.SetText(download_campaign.button_captions[_tc][download_campaign.campaigns[_tc].items[num_campaign].State])
	download_campaign.window.label_description.SetText(download_campaign.campaigns[_tc].items[num_campaign].Description)
end
	
download_campaign.on_button_buy_down = {}

download_campaign.on_button_buy_down[download_campaign.enum.pay] = function (_owner, _campaign, _num)
		
end

download_campaign.load_campaign = function ()

	if download_campaign.thread_proc_params.file == nil then
	
		print('function \'download_campaign.save_campaign_from_file invalid\': invalid parameters')
		io.flush()
		return
		
	end
	
	local campaign = s4.le.CCampaign()
	campaign.Load(download_campaign.thread_proc_params.file, true)
	s4.le.g_Campaigns.Instance().AddCampaign(campaign, false)
	
end
	
download_campaign.on_button_buy_down[download_campaign.enum.free] = function (_owner, _campaign, _num)
	
	local params_download_campaign = {}
	
	if _campaign.State == download_campaign.enum.updated then
	
		params_download_campaign.dialog_main = _T("s4_download_update_campaign")
		params_download_campaign.dialog_transfer_error = _T("s4_download_update_error")
		params_download_campaign.dialog_cancel = _T("s4_download_update_cancel")
		params_download_campaign.dialog_complete = _T("s4_download_update_complete")
		
	else
	
		params_download_campaign.dialog_main = _T("s4_download_download_campaign")
		params_download_campaign.dialog_transfer_error = _T("s4_download_download_error")
		params_download_campaign.dialog_cancel = _T("s4_download_download_cancel")
		params_download_campaign.dialog_complete = _T("s4_download_download_complete")
	
	end
	
	download_campaign.campaign_name = _campaign.Name
	params_download_campaign.dialog_connection_error = _T("s4_download_connection")
	params_download_campaign.url = download_campaign.url_campaigns + _campaign.FileName

	params_download_campaign.outfile = s4.le.g_Campaigns.Instance().MakeFilePath()
	params_download_campaign.func_prepare_dialog_main = download_campaign.func_prepare_download_campaign
	params_download_campaign.func_prepare_dialog_cancel = download_campaign.func_prepare_download_campaign_cancel
	
	local result_download_campaign = download.http_request(_owner, params_download_campaign)
	
	if result_download_campaign ~= download.enum.successful then return end
	
	sf.misc.SetNamedFullAccess(params_download_campaign.outfile, false)
	
	local dialog_download_complete = sf.gui.CWindow()
	game.load_window(_owner, dialog_download_complete, params_download_campaign.dialog_complete)
	
	local label_text = __cast(dialog_download_complete.GetWidget(_T("label_text")), sf.gui.CLabelWidget)
	local text = std.wstring(label_text.GetText())
	label_text.SetText(_T(string.format(T_(text).c_str(), T_(_campaign.Name).c_str())))
	
	local dialog_download_complete_ptr = sf.gui.CBaseWindowPtrT(dialog_download_complete)
	_owner.DoModal(dialog_download_complete_ptr)
	
	local campaign_header = s4.le.CCampaign()
	campaign_header.Load(params_download_campaign.outfile, false)
	
	if _campaign.State == download_campaign.enum.updated then
		s4.le.g_Campaigns.Instance().RemoveCampaign(campaign_header.GetGUIDStr())
	end
		
	s4.le.g_Campaigns.Instance().AddCampaign(s4.le.CCampaign(), false)
	local campaign = s4.le.g_Campaigns.Instance().GetCampaign(s4.le.g_Campaigns.Instance().EnumCampaigns()-1)
	campaign.Load(params_download_campaign.outfile, false)
				
	local num_after_remove = _num

	if _num == download_campaign.campaigns[download_campaign.enum.free].count then
		num_after_remove = num_after_remove-1
	end
	
	download_campaign.campaigns[download_campaign.enum.free].count = download_campaign.campaigns[download_campaign.enum.free].count-1
	table.remove(download_campaign.campaigns[download_campaign.enum.free].items, _num)
	download_campaign.fill_table(_owner, download_campaign.enum.free)

	download_campaign.campaigns[download_campaign.enum.free].table.SelectRow(num_after_remove)
		
end

download_campaign.on_child_action = {}
	
download_campaign.on_child_action.s4_download_campaign_window = function(_owner, _action, _child)

	if _action == _T("pressed") then
	
		if _child.GetId() == _T("button_buy") then
		
			-- AHTUNG
			--local tc = download_campaign.window.tab_panel.GetSelectedPanel()		
			local tc = download_campaign.enum.free
			local num_campaign = download_campaign.campaigns[tc].table.GetSelectedRow()
			
			if num_campaign~=-1 and num_campaign <= download_campaign.campaigns[tc].count and  download_campaign.campaigns[tc].count ~= 0 then
				download_campaign.on_button_buy_down[tc](_owner, download_campaign.campaigns[tc].items[num_campaign], num_campaign)
			end
		
		elseif _child.GetId() == _T("button_ok") then
		
			if _owner.GetParentWindow() then select_campaign.form_select_campaign_window(_owner.GetParentWindow(), false) end
			_owner.AddFlags(sf.gui.CBaseWidget.FlagDead)
			--_owner.EndModal(1)
		
		elseif _child.GetId() == _T("button_update_game") then
			
			if sf.misc.CheckExistPath(sf.misc.AppendPath(_T("game"), update_game.update_semaphore)) == true then
			
				update_game.restart_after_update(_owner, _T("s4_update_restart"))
				
			else
			
				local opt = update_game.options
				if opt.AvailableNewVersion then
					update_game.doit(_owner)
				else
					local dialog_no_changes = sf.gui.CWindow()
					game.load_window(_owner, dialog_no_changes, _T("s4_update_no_changes"))
					local dialog_no_changes_ptr = sf.gui.CBaseWindowPtrT(dialog_no_changes)
					_owner.DoModal(dialog_no_changes_ptr)
				end										
				
			end
		end
	
	elseif _action == _T("line_selected") and _child.GetId() == _T("combobox_sort_columns") then
		
		local selected_line = __cast(_child, sf.gui.CComboBoxWidget).GetSelectedLine();
		
		table.sort(download_campaign.campaigns[download_campaign.enum.pay].items, download_campaign.sort_func[selected_line])
		table.sort(download_campaign.campaigns[download_campaign.enum.free].items, download_campaign.sort_func[selected_line])
		
		--download_campaign.fill_table(_owner, download_campaign.enum.pay)
		download_campaign.fill_table(_owner, download_campaign.enum.free)
	
	elseif 	_child.GetId() == _T("tab_panel") or 
			_child.GetId() == download_campaign.tables[download_campaign.enum.pay] or 
			_child.GetId() == download_campaign.tables[download_campaign.enum.free] then
		
		-- AHTUNG
		--download_campaign.update_button_caption(_owner, download_campaign.window.tab_panel.GetSelectedPanel())
		download_campaign.update_button_caption(_owner, download_campaign.enum.free)
	
	end

end

download_campaign.is_already_loaded = function(_campaign)

	local num_campaigns = s4.le.g_Campaigns.Instance().EnumCampaigns()
	
	for i=0, num_campaigns-1 do

		local current_campaign = s4.le.g_Campaigns.Instance().GetCampaign(i)
		if current_campaign.GetGUIDStr() == _campaign.GUIDStr then
			
			local time1 = game.get_lua_time(current_campaign.GetLastUpdate())
			local time2 = game.get_lua_time(_campaign.LastUpdate)

			return true, (time1<time2)
		end
		
	end

	return false, false
end

download_campaign.is_new = function(_campaign)

	local campaign_time_lua = game.get_lua_time(_campaign.LastUpdate)
	local current_time_lua = os.time()
	
	local sec_per_week = 60*60*24*7;
	
	if (current_time_lua-campaign_time_lua)<=sec_per_week then
		return true
	else
		return false
	end
end

function download_campaign.try(_owner)
	
	local params_campaigns_info = {}
	params_campaigns_info.dialog_main = _T("s4_download_campaign_info")
	params_campaigns_info.dialog_connection_error = _T("s4_download_connection")
	params_campaigns_info.dialog_transfer_error = _T("s4_download_campaign_info_error")
	params_campaigns_info.dialog_cancel = _T("s4_download_campaign_info_cancel")
	params_campaigns_info.url = download_campaign.url_campaigns+_T("campaigns.xml")
	params_campaigns_info.outfile = _T("campaigns_info.xml")
	
	local result_get_campaigns_info = download.http_request(_owner, params_campaigns_info)
	
	if result_get_campaigns_info ~= download.enum.successful then return end
	
	local window_campaigns = sf.gui.CWindow()
	game.load_window(_owner, window_campaigns, _T("s4_download_campaign_window"))
	window_campaigns.SetCanDrag(false)
	local window_campaigns_ptr = sf.gui.CBaseWindowPtrT(window_campaigns)
	
	update_game.run_check_update(window_campaigns_ptr)
	
	download_campaign.window.tab_panel = __cast(window_campaigns.GetWidget(_T("tab_panel")), sf.gui.CTabWidget)
	
	-- AHTUNG
	--[[
	for i=0, 1 do
			
		download_campaign.campaigns[i] = {}
			
		download_campaign.campaigns[i].count = 0
			
		download_campaign.campaigns[i].items = {}
			
		download_campaign.campaigns[i].rowinfo = 
			download.app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_download_campaign_window"), true).
				GetChildByAttribute(_T("table_widget"), _T("id"), download_campaign.tables[i], true).GetChild(_T("table_widget_rows"), true).
					GetFirstChild()
		
		download_campaign.campaigns[i].table = __cast(download_campaign.window.tab_panel.GetPanelContent(i).
				GetWidget(download_campaign.tables[i]), sf.gui.CTableWidget)
	end]]
	
	-----------------------------
	
	for i=0, 1 do
			
		download_campaign.campaigns[i] = {}
			
		download_campaign.campaigns[i].count = 0
			
		download_campaign.campaigns[i].items = {}
		
	end
	
	download_campaign.campaigns[1].rowinfo = 
		download.app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_download_campaign_window"), true).
			GetChildByAttribute(_T("table_widget"), _T("id"), download_campaign.tables[1], true).GetChild(_T("table_widget_rows"), true).
				GetFirstChild()
	
	download_campaign.campaigns[1].table = __cast(download_campaign.window.tab_panel.GetPanelContent(0).
			GetWidget(download_campaign.tables[1]), sf.gui.CTableWidget)
	
	-----------------------------

	download_campaign.window.button_buy = __cast(window_campaigns.GetWidget(_T("button_buy"), true), sf.gui.CButtonWidget)
	download_campaign.window.label_description = __cast(window_campaigns.GetWidget(_T("label_description"), true), sf.gui.CLabelWidget)
			
	local settings = sf.core.CSettings()
	settings.LoadXml(params_campaigns_info.outfile)

	local group_campaigns = settings.GetChild(_T("Campaigns"), false)
	local group_campaign = group_campaigns.GetFirstChild()
	
	local sec_per_day = 60*60*24;
	
	while group_campaign.GetId().empty()==false do
		
		if group_campaign.GetId() == _T("campaign") then
			
			local tc = download_campaign.enum.pay
			if group_campaign.GetValue(_T("type")) ~= _T("pay") then tc = download_campaign.enum.free end
			
			local campaign = {}
			
			campaign.GUIDStr = group_campaign.GetValue(_T("guid"))
			campaign.Name = group_campaign.GetValue(_T("id"))
			campaign.Author = group_campaign.GetValue(_T("author"))
			campaign.Description = group_campaign.GetValue(_T("description"))		
			campaign.FileName = group_campaign.GetValue(_T("file_name"))
			campaign.BonusBrickTemplate = group_campaign.GetValue(_T("bonus_brick_template"))
			campaign.LevelCount = s4.StringToInt(group_campaign.GetValue(_T("levels")))
			campaign.AverRating = s4.StringToFloat(group_campaign.GetValue(_T("average_rating")))
			campaign.LastUpdate = s4.StringToTime(group_campaign.GetValue(_T("last_update")))
			campaign.MinVersion = s4.StringToIntVector(group_campaign.GetValue(_T("min_version")))
			
			local already_loaded, need_update = download_campaign.is_already_loaded(campaign)
			
			if not already_loaded then
			
				local viewed_campaign = download_campaign.options.AddViewedCampaign(campaign.GUIDStr)
				
				if 	(	(viewed_campaign ~= nil and os.time() - game.get_lua_time(viewed_campaign.ViewTime) < sec_per_day) or 
						(viewed_campaign == nil)	) and download_campaign.is_new(campaign) then
						
					campaign.State = download_campaign.enum.new
					
				else
				
					campaign.State = download_campaign.enum.old
					
				end
				
				download_campaign.campaigns[tc].count = download_campaign.campaigns[tc].count+1
				download_campaign.campaigns[tc].items[download_campaign.campaigns[tc].count] = {}
				download_campaign.campaigns[tc].items[download_campaign.campaigns[tc].count] = campaign
				
			elseif need_update then
			
				campaign.State = download_campaign.enum.updated
				download_campaign.campaigns[tc].count = download_campaign.campaigns[tc].count+1
				download_campaign.campaigns[tc].items[download_campaign.campaigns[tc].count] = {}
				download_campaign.campaigns[tc].items[download_campaign.campaigns[tc].count] = campaign
				
			end
						
		end

		group_campaign = group_campaign.GetNextSibling()
		
	end
	
	sf.misc.ShDeleteFile(params_campaigns_info.outfile)
		
	download_campaign.window.combobox_sort_columns = __cast(window_campaigns.GetWidget(_T("combobox_sort_columns")), sf.gui.CComboBoxWidget)
	download_campaign.window.combobox_sort_columns.SelectLine(1, true)
	
	_owner.AddChildWindow(window_campaigns_ptr)
		
	--[[if _owner.DoModal(window_campaigns_ptr) == 2 then
	
		local s4app = __cast(download.app, s4.CS4App)
		s4app.SetNeedRestart(true)
		download.app.Shutdown()
	
	end]]
	
end
