select_campaign = {}

select_campaign.TabNames = {
				easy_table = "Easy",
				normal_table = "Normal",
				hard_table = "Hard",
				expert_table = "Expert"
			}
select_campaign.OutputTabs = {}

os.setlocale("", "time")

function compare_string(_s1, _s2)
	
	local str1 = T_(sf.misc.g_StringTable.Instance().FormatByStringsID(_s1)).c_str()
	local str2 = T_(sf.misc.g_StringTable.Instance().FormatByStringsID(_s2)).c_str()
	
	return sf.misc.StringCompare(_T(string.lower(str1)), _T(string.lower(str2)))
	
end

function select_campaign.form_select_campaign_window(_owner, _select_last_game)
		local app = sf.core.g_Application

		local game_camapgins = get_camapigns_info()
		local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile();
		local p_c_h = get_profile_info(current_profile)
		
		select_campaign.OutputTabs = {}
		for dif_level_id in pairs(diff_levels) do
			select_campaign.OutputTabs[dif_level_id] = {}
			select_campaign.OutputTabs[dif_level_id].campaigns = {}
			comp_num = 1
			for camp_id in pairs(game_camapgins) do
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num] = {}
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].Name = game_camapgins[camp_id].Name
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].GUID = game_camapgins[camp_id].GUID
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].camp_list_id = camp_id
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].PlayerRatingWidget = false

				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].NumLevels = game_camapgins[camp_id].NumLevels
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LevelsFinished = 0
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LastGD = nil
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LastGameLevel = 0
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].IsRatingAviable = game_camapgins[camp_id].IsRatingAviable
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].AvRating = game_camapgins[camp_id].Rating
				select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].RatingByPlayer = -1
				if p_c_h[camp_id] then
					select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LastGameLevel = p_c_h[camp_id].common_info.MaxLevelFinished
					select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].RatingByPlayer = p_c_h[camp_id].common_info.Rating
					
					if p_c_h[camp_id].dif_levels[dif_level_id] then
						select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LevelsFinished = p_c_h[camp_id].dif_levels[dif_level_id].LevelsFinished
						select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LastGameLevel = p_c_h[camp_id].dif_levels[dif_level_id].LastGameLevel
						select_campaign.OutputTabs[dif_level_id].campaigns[comp_num].LastGD = p_c_h[camp_id].dif_levels[dif_level_id].LastGD						
					end
				end
				comp_num = comp_num + 1		
			end
		end
		
		SortFunctions = {}
		SortFunctions[0] = function (a , b) --"Name"
							if a.IsRatingAviable ~= b.IsRatingAviable then
								return not a.IsRatingAviable
							end
							return not compare_string(b.Name, a.Name)
						end 
		SortFunctions[1] = function (a , b) --"Date"
							if a.IsRatingAviable ~= b.IsRatingAviable then
								return not a.IsRatingAviable
							end
							if game.is_correct_time(a.LastGD) ~= game.is_correct_time(b.LastGD) then
								return game.is_correct_time(a.LastGD)
							end
							if game.is_correct_time(a.LastGD) and game.is_correct_time(b.LastGD) and 
								game.get_lua_time(a.LastGD) ~= game.get_lua_time(b.LastGD) then
								return (game.get_lua_time(a.LastGD) > game.get_lua_time(b.LastGD))
							end
							return not compare_string(b.Name, a.Name)
						end 
		SortFunctions[2] = function (a , b) --"Num of Levels"
							if a.IsRatingAviable ~= b.IsRatingAviable then
								return not a.IsRatingAviable
							end
							if a.NumLevels ~= b.NumLevels then
								return a.NumLevels > b.NumLevels
							end
							return not compare_string(b.Name, a.Name)
						end 
		SortFunctions[3] = function (a , b) --"RatingA"
							if a.IsRatingAviable ~= b.IsRatingAviable then
								return not a.IsRatingAviable
							end
							if  a.AvRating ~= b.AvRating then
								return a.AvRating > b.AvRating
							end
							return not compare_string(b.Name, a.Name)
						end 
		SortFunctions[4] = function (a , b) --"RatingP"
							if a.IsRatingAviable ~= b.IsRatingAviable then
								return not a.IsRatingAviable
							end
							if a.RatingByPlayer ~= b.RatingByPlayer then
								return a.RatingByPlayer > b.RatingByPlayer
							end
							return not compare_string(b.Name, a.Name)
						end 
		
		local sort_combo_box = __cast(_owner.GetWidget("sort_combobox"), sf.gui.CComboBoxWidget)
		local sort_function = SortFunctions[sort_combo_box.GetSelectedLine()] --T_(sort_combo_box.GetLine(--)).c_str()

		for dl in pairs(diff_levels) do
			table.sort  (select_campaign.OutputTabs[dl].campaigns,  sort_function)
		end
		
		local header_row = app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute( 
			_T("window"), _T("id"), _T("s4_select_campagin"), true).GetChildByAttribute(
				_T("table_widget"), _T("id"), _T("easy_table"), true).GetNamedChild(_T("rows"), false).GetChild(_T("row"), false)
		local string_row = header_row.GetNextSibling()

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

		OutputTableWidgets = 
		{
			Easy = __cast(_owner.GetWidget("easy_table",true), sf.gui.CTableWidget),
			Normal = __cast(_owner.GetWidget("normal_table",true), sf.gui.CTableWidget),
			Hard = __cast(_owner.GetWidget("hard_table",true), sf.gui.CTableWidget),
			Expert = __cast(_owner.GetWidget("expert_table",true), sf.gui.CTableWidget)
		}

		for d in pairs(diff_levels) do
			OutputTableWidgets[d].ClearTable()
			OutputTableWidgets[d].LoadRow(header_row, template)
		end
		
		for dif_id in pairs(diff_levels) do
			local camp_num = 1
			for camp_id in pairs(select_campaign.OutputTabs[dif_id].campaigns) do
			
				
				OutputTableWidgets[dif_id].LoadRow(string_row, template)
				local label_num = __cast(OutputTableWidgets[dif_id].GetCell(camp_num, 0).GetWidgets().Get(), sf.gui.CLabelWidget)
				label_num.SetText(_T(tostring(camp_num)))
				label_num.ResizeToFitText(false);
				OutputTableWidgets[dif_id].GetCell(camp_num, 0).UpdateLayout()
				
				local out_string = T_(select_campaign.OutputTabs[dif_id].campaigns[camp_id].Name)
				--log(T_(select_campaign.OutputTabs[dif_id].campaigns[camp_num].Name))
				local label_name = __cast(OutputTableWidgets[dif_id].GetCell(camp_num, 1).GetWidgets().Get(), sf.gui.CLabelWidget)
				label_name.SetText(sf.misc.g_StringTable.Instance().FormatByStringsID(_T(out_string)).c_str())
					--SetText(_T("123"))
				label_name.ResizeToFitText(false);
				OutputTableWidgets[dif_id].GetCell(camp_num, 1).UpdateLayout()
				
				local finished_levels = select_campaign.OutputTabs[dif_id].campaigns[camp_id].LevelsFinished
				local total_levels = select_campaign.OutputTabs[dif_id].campaigns[camp_id].NumLevels
				
				out_string = string.format("%d/%d", finished_levels, total_levels)
				local label_level = __cast(OutputTableWidgets[dif_id].GetCell(camp_num, 2).GetWidgets().Get().get(), "sf.gui.CLabelWidget")
				label_level.SetText(_T(out_string))
				label_level.ResizeToFitText(false);
				OutputTableWidgets[dif_id].GetCell(camp_num, 2).UpdateLayout()
				
				local last_level = select_campaign.OutputTabs[dif_id].campaigns[camp_id].LastGameLevel+1
				if finished_levels == total_levels then last_level = last_level-1 end

				if game.is_correct_time(select_campaign.OutputTabs[dif_id].campaigns[camp_id].LastGD) then
					out_string = string.format("%d %s %s", 
						last_level, 
						T_(sf.misc.g_StringTable.Instance().FormatByStringsID(_T("$771"))).c_str(),
						os.date("%x", game.get_lua_time(select_campaign.OutputTabs[dif_id].campaigns[camp_id].LastGD)))
				else
					out_string = ""
				end
				
				local label_date = __cast(OutputTableWidgets[dif_id].GetCell(camp_num, 3).GetWidgets().Get().get(), "sf.gui.CLabelWidget")
				label_date.SetText(_T(out_string))
				label_date.ResizeToFitText(false);
				OutputTableWidgets[dif_id].GetCell(camp_num, 3).UpdateLayout()
				
				local widget_av_rating = __cast(OutputTableWidgets[dif_id].GetCell(camp_num, 4).GetWidgets().Get().get(), "s4.CFixedSliderWidget")
				local widget_pl_rating = __cast(OutputTableWidgets[dif_id].GetCell(camp_num, 5).GetWidgets().Get().get(), "s4.CFixedSliderWidget")
				
				select_campaign.OutputTabs[dif_id].campaigns[camp_id].PlayerRatingWidget = widget_pl_rating;
				
				set_widget_flag_value(widget_av_rating, sf.gui.CBaseWidget.FlagHidden, false)
				
				local av_rating = select_campaign.OutputTabs[dif_id].campaigns[camp_id].AvRating
				local pl_rating = select_campaign.OutputTabs[dif_id].campaigns[camp_id].RatingByPlayer			
				
				local value = 0
				
				if av_rating == -1  then value=10 else value=av_rating*2 end
				widget_av_rating.SetValue(value, false)
				
				if pl_rating == -1  then value=1 else value=pl_rating end
				widget_pl_rating.SetValue(value, false)
				
				if select_campaign.OutputTabs[dif_id].campaigns[camp_id].IsRatingAviable == false then
					set_widget_flag_value(widget_pl_rating, sf.gui.CBaseWidget.FlagHidden, true)
				end

				camp_num = camp_num + 1 			
			end
			
		end
		
		for d in pairs(diff_levels) do
			OutputTableWidgets[d].FitCells() 
			if select_campaign.OutputTabs["Easy"].campaigns[1]  then
				OutputTableWidgets[d].SelectRow(1)
			end
		end
end
			
			
function select_campaign.update_game(_owner, _campaign_id)				

	print('abra')
	io.flush()
	if sf.misc.CheckExistPath(sf.misc.AppendPath(_T("game"), update_game.update_semaphore)) then
		
		update_game.restart_after_update(_owner, _T("s4_update_restart_for_campaign"))
		
	else
		
		update_game.options.AvailableNewVersion = true
		
		local dialog_update_for_campaign = s4.COnKeyDownWindow()
		game.load_window(_owner, dialog_update_for_campaign, _T("s4_update_for_campain"))
		local dialog_update_for_campaign_ptr = sf.gui.CBaseWindowPtrT(dialog_update_for_campaign)
		
		local label_text = __cast(dialog_update_for_campaign.GetWidget(_T("label_text")), sf.gui.CLabelWidget)
		label_text.SetText(_T(string.format(T_(label_text.GetText()).c_str(), T_(_campaign_id).c_str())))
		
		local res = _owner.DoModal(dialog_update_for_campaign_ptr)
		
		if res == 0 then
			update_game.doit(_owner)				
		elseif res == 1 then
			update_game.options.LastAttemptResult = s4.CGameOptions.UpdateOptions.Denied
		elseif res == 2 then
			update_game.options.LastAttemptResult = s4.CGameOptions.UpdateOptions.RemindLater
		end									
	end			
end

function select_campaign.select_campagin_script(_owner, _action, _child)

	local app = sf.core.g_Application

	if (_child.GetId()==_T("play_button") and _action==_T("pressed")) or (_action==_T("table_double_click")) then
		local test_tab = __cast(_owner.GetWidget(_T("difficulty_levels_tab"), true).get(), "sf.gui.CTabWidget")
		local get_tab = test_tab.GetPanelContent( test_tab.GetSelectedPanel())
		local current_table = __cast(get_tab.GetWidgets().Get().get(), "sf.gui.CTableWidget")
		local row_num = current_table.GetSelectedRow()
		if (row_num ~= -1) and (row_num ~= 0) then
			--local camp_name = sf.gui.CastCLabelWidget(current_table.GetCell(row_num, 1).GetWidgets().Get().get()).GetText()
			--log ("selected tab table id = "..select_campaign.TabNames[T_(current_table.GetId())])
			--log ("selected campaign id = "..T_(camp_name))

			--local camp_name_ = T_(camp_name)
			
			local dif_level_name_ = select_campaign.TabNames[T_(current_table.GetId()).c_str()]
			local camp_GUID = select_campaign.OutputTabs[dif_level_name_].campaigns[row_num].GUID
			
			local campaign = s4.le.g_Campaigns.Instance().GetCampaignByGUID(camp_GUID);
			print('camp '..campaign.GetMinVersion().X..','..campaign.GetMinVersion().Y)
			print('game '..game.version.X..','..game.version.Y)
			io.flush()
			if (campaign.GetMinVersion().X > game.version.X) or
				(campaign.GetMinVersion().X == game.version.X and campaign.GetMinVersion().Y > game.version.Y) then
				select_campaign.update_game(_owner, campaign.GetId())				
			else
			
				local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
				local last_played_campaign = current_profile.GetLastPlayedCampaignId()
				local last_played_dif_level = current_profile.GetLastPlayedDifficultyLevelId()
				local game_camapgins = get_camapigns_info()
				local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
				local p_c_h = get_profile_info(current_profile)
				
				local camp_info  = p_c_h[T_(camp_GUID).c_str()]
				if camp_info then
					local game_info = camp_info.dif_levels[dif_level_name_]
					if game_info then
						if camp_info.common_info.NumLevels == game_info.LastGameLevel and camp_info.NumLevels ~= 0 then 
						
							select_level.run_select_level_window(_owner, camp_info, dif_level_name_, 0)
							-- выбор уровня для только что законченой игры
						else
							select_campaign.run_continue_or_new_campaign_dialog(_owner, camp_info, dif_level_name_)
							-- диалог о продолжении игры
						end
					else
						select_level.run_select_level_window(_owner, camp_info, dif_level_name_, camp_info.common_info.MaxLevelFinished)
						-- играл но на другом уровне сложности окно выбора уровня
					end
				else
					s4.g_Difficulty.Instance().SetDifficultyLevel(diff_levels_enum[dif_level_name_])
					main_menu.start_game(_owner, camp_GUID, 0, 0, 0, game.StartLivesNum, false) 

					-- еще не играл в компанию начинаем сходу игру
				end
			end
		end
	
	elseif _child.GetId()==_T("delete_button") and _action==_T("pressed") then
		local test_tab = __cast(_owner.GetWidget(_T("difficulty_levels_tab")), sf.gui.CTabWidget)
		local get_tab = test_tab.GetPanelContent( test_tab.GetSelectedPanel())
		local current_table = __cast(get_tab.GetWidgets().Get(), sf.gui.CTableWidget)
		local row_num = current_table.GetSelectedRow()
		if row_num ~= -1 then
			local dif_level_name_ = select_campaign.TabNames[T_(current_table.GetId()).c_str()]
			local comp_GUID = select_campaign.OutputTabs[dif_level_name_].campaigns[row_num].GUID
			
			if	sf.misc.BitwiseAnd(s4.le.g_Campaigns.Instance().GetCampaignByGUID(comp_GUID).GetFlags(), s4.le.CCampaign.FlagCanNotBeDelete) ~= 0 then
				s4.ModalWindow(_T("dialog_can_not_delete_campaign"),_owner)
			else
				local window = s4.COnKeyDownWindow()
				window.Load(
					app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("dialog_delete_campaign_confirmation"), true), 
					app.GetSettings().GetChild(_T("GUITemplates"), false))
				window.UpdateLayout()   
				MoveWindowToCenter(_owner, window)
				
				local window_ptr = sf.gui.CBaseWindowPtrT(window)
				
				local modal_res = _owner.DoModal(window_ptr)
				window_ptr = nil
				collectgarbage()			
				if  modal_res == 1  then
					s4.le.g_Campaigns.Instance().RemoveCampaign(comp_GUID)
					select_campaign.form_select_campaign_window(_owner, false)
				end
			end
			
			
			
		end

	--	select_campaign.form_select_campaign_window(_owner, false)
--		dofile("scripts\\game\\new_campaigns.lua")
	--	if get_new_campaigns_info(_owner) == 1 then
		--	select_campaign.form_select_campaign_window(_owner, false)
		--end
	elseif _action==_T("value_changed") then --_child.GetId()==_T("player_rating") and 
		local child_id = _child.GetId()
		if child_id == _T("average_rating") or child_id == _T("player_rating") then

			fixed_slider_widget = __cast(_child, "s4.CFixedSliderWidget")

			local new_value = fixed_slider_widget.GetValue()
			
			log("new_value = "..tostring(new_value))
			local test_tab = __cast(_owner.GetWidget(_T("difficulty_levels_tab"), true).get(), "sf.gui.CTabWidget")
			local get_tab = test_tab.GetPanelContent( test_tab.GetSelectedPanel())
			local current_table = __cast(get_tab.GetWidgets().Get().get(), "sf.gui.CTableWidget")
			local row_num = current_table.GetSelectedRow()
			if row_num ~= -1 then
				local dif_level_name_ = select_campaign.TabNames[T_(current_table.GetId()).c_str()]
				local comp_GUID = select_campaign.OutputTabs[dif_level_name_].campaigns[row_num].GUID
				local comp_Name = select_campaign.OutputTabs[dif_level_name_].campaigns[row_num].Name
				
				select_campaign.OutputTabs[dif_level_name_].campaigns[row_num].RatingByPlayer = new_value

				local current_profile = s4.g_ProfileManager.Instance().GetCurrentProfile()
				local changed_campaign = current_profile.GetCampaignByGUID(comp_GUID)
				if changed_campaign then
					log("change_rating"..tostring(new_value))
					changed_campaign.Rating = new_value
				else
					log("insert campaign"..T_(comp_Name).c_str().." "..T_(comp_GUID).c_str().." "..tostring(new_value))
					local new_camp_info = s4.CampaignInfo(comp_Name, new_value, comp_GUID)
					--new_camp_info.Id = comp_Name
					--new_camp_info.GUID = comp_GUID
					--new_camp_info.Rating = new_value
					current_profile.AddCampaign(new_camp_info)
				
				end

				for dif_id in pairs(diff_levels) do
					for camp_id in pairs(select_campaign.OutputTabs[dif_id].campaigns) do
						if select_campaign.OutputTabs[dif_id].campaigns [camp_id].GUID == comp_GUID then
							log("find_camp = "..T_(comp_GUID).c_str())
							log("find_camp ID = "..T_(select_campaign.OutputTabs[dif_id].campaigns [camp_id].Name).c_str())
							select_campaign.OutputTabs[dif_id].campaigns [camp_id].RatingByPlayer = new_value
							--set_widget_flag_value(select_campaign.OutputTabs[dif_id].campaigns [camp_id].PlayerRatingWidget, sf.gui.CBaseWidget.FlagHidden, true)
							select_campaign.OutputTabs[dif_id].campaigns [camp_id].PlayerRatingWidget.SetValue(new_value, false)
							
						end
					end
				end

				
				--s4.le.g_Campaigns.Instance().RemoveCampaign(comp_GUID)
				--select_campaign.form_select_campaign_window(_owner, false)
				
			end
		end
	
	elseif _child.GetId()==_T("sort_combobox") and _action==_T("line_selected") then
		select_campaign.form_select_campaign_window(_owner, false)
		
	elseif _child.GetId()==_T("get_new_campaigns_button") and _action==_T("pressed") then
		s4.g_MainLua.LoadScript(_T("scripts\\game\\download_campaign.lua"))
		download_campaign.try(_owner)
		
	elseif _child.GetId()==_T("cancel_button") and _action==_T("pressed") or _action == _T("key_down_escape") then
		_owner.AddFlags(sf.gui.CBaseWidget.FlagDead)
		--_owner.GetParentWindow().RemoveChildWindow()
	end
end
			
function select_campaign.run_continue_or_new_campaign_dialog(_owner, _camp_info, _dif_level_id)
	local app = sf.core.g_Application
	local window = s4.COnKeyDownWindow()
	window.Load(
		app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s4_continue_or_new_game"), true), 
		app.GetSettings().GetChild(_T("GUITemplates"), false))
	window.UpdateLayout()                                             
	MoveWindowToCenter(_owner, window)
	window_ptr = sf.gui.CBaseWindowPtrT(window)
	local modal_result = _owner.DoModal(window_ptr)
	window_ptr = nil
	collectgarbage()

	if modal_result == 2 then
		select_level.run_select_level_window(_owner, _camp_info, _dif_level_id, 0)
	elseif modal_result == 1 then
		local current_game = _camp_info.dif_levels[_dif_level_id]
		if current_game then
			s4.g_Difficulty.Instance().SetDifficultyLevel(diff_levels_enum[_dif_level_id])
			main_menu.start_game(_owner, _camp_info.GUIDStr, current_game.LastGameLevel, current_game.LastGamePoints, current_game.LastGameGems, current_game.LastGameLifes, false) 
		end
	end
end

local function clear_cache()
	s4.le.g_Campaigns.Instance().ClearCache()
	sf.core.g_Application.GetResourceManager().CollectUnusedResources()
end

function select_campaign.continue_or_new_game_script(_owner, _action, _child)
	if _child.GetId()==_T("new_game") and _action==_T("pressed") then
		clear_cache()
		_owner.EndModal(2)
	elseif _child.GetId()==_T("continue") and _action==_T("pressed") or _action == _T("key_down_enter") then
		clear_cache()
		_owner.EndModal(1)	
	elseif _child.GetId()==_T("cancel") and _action==_T("pressed") or _action == _T("key_down_escape") then
		clear_cache()
		_owner.EndModal(0)	
	end
end
