profile_edit_window_dialog = profile_edit_window_dialog or {}
profile_edit_window_dialog.actions = profile_edit_window_dialog.actions or {}

profile_edit_window_dialog.actions.ok_modify = 
{
	pressed = function(_window) 
        user_profiles.run_modify_function(_window)
	end
}

profile_edit_window_dialog.actions.cancel = 
{
	pressed = function(_window) 
        _window.EndModal(0)
	end
}

profile_edit_window_dialog.actions.no = 
{
	pressed = function(_window) 
        _window.EndModal(0)
	end
}

profile_edit_window_dialog.actions.yes = 
{
	pressed = function(_window) 
        _window.EndModal(1)
	end
}
profile_edit_window_dialog.actions.ok = 
{
	pressed = function(_window) 
        _window.EndModal(1)
	end
}

profile_edit_window_dialog.actions.edit = 
{
	text_changed = function(_window) 
        profile_edit_window_dialog.TestEmptyName(_window )
	end
}

    


function profile_edit_window_dialog.Show(_objects, _window)
end

function profile_edit_window_dialog.DoDraw(_this, _renderer)
end

function profile_edit_window_dialog.DoUpdate(_this)
end

function profile_edit_window_dialog.TestEmptyName(_this )
    local edit_widget = _this.GetWidget(_T("edit")).get()
    if edit_widget then
        edit_widget = __cast(edit_widget, sf.gui.CEditWidget)
        if edit_widget then
            local edit_text = edit_widget.GetText()
            
            local button_widget = _this.GetWidget(_T("ok_modify")).get()
            button_widget = __cast(button_widget, sf.gui.CButtonWidget)
            if button_widget then
                if edit_text == _T("") then
                    button_widget.DisableButton(true)
                else
                    button_widget.DisableButton(false)
                end
            end
        end
    end
end

function profile_edit_window_dialog.OnChar(_this, _char, _keyboard_state, _state, _broadcast)
	return _this.SuperOnChar(_char, _keyboard_state, _state, _broadcast)
end

function profile_edit_window_dialog.OnKeyDown(_this, _key, _keyboard_state, _state, _broadcast)
    if (_this.GetId().c_str() == "s10_new_user" or _this.GetId().c_str() == "s10_rename_user") and _key == 13 then
        _this.SetChildFocused(nil)

    end

	if _this.SuperOnKeyDown( _key, _keyboard_state, _state, _broadcast) then
        return true
    end
    
    return false
end

function profile_edit_window_dialog.OnKeyUp(_this, _key, _keyboard_state, _state, _broadcast)
	return _this.SuperOnKeyUp( _key, _keyboard_state, _state, _broadcast)
end

function profile_edit_window_dialog.OnMouseMove(_this, _pos, _state, _broadcast)
	return _this.SuperOnMouseMove( _pos, _state, _broadcast) 
end

function profile_edit_window_dialog.OnMouseDown(_this, _pos, _button, _state, _broadcast)
	return _this.SuperOnMouseDown( _pos, _button, _state, _broadcast)
end

function profile_edit_window_dialog.OnMouseUp(_this, _pos, _button, _state, _broadcast)
	return _this.SuperOnMouseUp( _pos, _button, _state, _broadcast) 
end

function profile_edit_window_dialog.OnDoubleClick(_this, _pos, _state, _broadcast)
	return _this.SuperOnDoubleClick( _pos, _state, _broadcast) 
end

function profile_edit_window_dialog.OnMouseWheel(_this, _pos, _delta, _state, _broadcast)
	return _this.SuperOnMouseWheel( _pos, _delta, _state, _broadcast)
end

function profile_edit_window_dialog.OnChildAction(_this, _action, _child)
	if not _child then return end
	local handler = profile_edit_window_dialog.actions[_child.GetId().c_str()]
	if handler then handler = handler[_action.c_str()] end
	if handler then handler(_this, _child) end
end

user_profiles = {}
user_profiles.temp_profile = _T("")

user_profiles.new_player_string_id = sf.misc.g_StringTable.Instance().FormatByStringsID("$353")

user_profiles.current_modify_window_type = nil



function user_profiles.run_profiles_dialog(_owner)
	local app = sf.core.g_Application			
	--local window = game.COnKeyDownWindow()
    local window = sf.gui.CWindow()

	window.Load(
		app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s10_user_profiles"), true), 
		app.GetSettings().GetChild(_T("GUITemplates"), false))
	window.UpdateLayout()
	MoveWindowToCenter(_owner, window)

	user_profiles.temp_profile = _T("")
	local current_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
	if current_profile ~= nil then
		user_profiles.temp_profile = current_profile.GetName()
	end

	local list_widget = __cast(window.GetWidget(_T("profiles_list")).get(), "sf.gui.CListWidget")
	if list_widget then
	
		user_profiles.update_list_with_profiles(list_widget)
	end

	local window_ptr = sf.gui.CBaseWindowPtrT(window)
	_owner.DoModal(window_ptr)
	window_ptr = nil
	collectgarbage()

end


function user_profiles.run_modify_function(_owner)
    if user_profiles.current_modify_window_type == "new" then
		local edit_widget = __cast(_owner.GetWidget(_T("edit")).get(), "sf.gui.CEditWidget")
		local edit_text = edit_widget.GetText()
		if edit_text == _T("") then
			--user_profiles.run_empty_user_name_dialog(_owner)
            user_profiles.run_dialog(_owner, "empty")
		else
			local find_profile_res = game.g_ProfileManager.Instance().GetProfile(edit_text)
			if find_profile_res then
					--user_profiles.run_dublicate_profile_dialog(_owner)
                    user_profiles.run_dialog(_owner, "dublicate")
			else
				local temp_text = std.wstring(edit_text)
				--edit_text = string.gsub(edit_text.c_str(), '%$', 'S')
				edit_text = qe.ReplaceDollarByS(edit_text);
				game.g_ProfileManager.Instance().CreateProfile(edit_text, true)

				local widget_ = _owner.GetParentWindow().GetWidget(_T("profiles_list")).get()
				if widget_ then
					local list_widget = __cast(widget_,		"sf.gui.CListWidget")
					if list_widget then
						user_profiles.update_list_with_profiles(list_widget)
					end
				end
				_owner.EndModal(1)
			end
		end

    elseif user_profiles.current_modify_window_type == "rename" then
		local edited_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
		local profile_name = edited_profile.GetName()
		local widget_ = _owner.GetParentWindow().GetWidget(_T("profiles_list")).get()
		if widget_ then

			local list_widget = __cast(widget_,		"sf.gui.CListWidget")
			if list_widget then
				current_line = list_widget.GetSelectedLine()
				if current_line ~= -1 then
					profile_name = list_widget.GetLine(current_line)
				end
			end
		end
		local edit_widget = __cast(_owner.GetWidget(_T("edit")).get(), "sf.gui.CEditWidget")
		local edit_text = edit_widget.GetText()
		if edit_text ~= _T("") then
			local current_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
			local find_profile_res = game.g_ProfileManager.Instance().GetProfile(edit_text)
			if  current_profile ~= nil and find_profile_res ~= nil  and current_profile.GetName() ~= edit_text then
					--user_profiles.run_dublicate_profile_dialog(_owner)
                    user_profiles.run_dialog(_owner, "dublicate")
			else
                    --edit_text = string.gsub(edit_text.c_str(), '%$', 'S')
					edit_text = qe.ReplaceDollarByS(edit_text);
					game.g_ProfileManager.Instance().Rename(profile_name, edit_text)
					--local renamed_curent_profile = game.g_ProfileManager.Instance().GetCurrentProfile() 
					--renamed_curent_profile.SetName(edit_text)
					_owner.EndModal(1)
			end
		else
			--user_profiles.run_empty_user_name_dialog(_owner)
            user_profiles.run_dialog(_owner, "empty")
		end
    else
        return
    end
end

function user_profiles.run_modify_name_dialog(_owner, _window_type, _disable_cancel)
    user_profiles.current_modify_window_type = _window_type

    local window_id = _T("")
    if _window_type == "new" then
        window_id = _T("s10_new_user")
    elseif _window_type == "rename" then
        window_id = _T("s10_rename_user")
    else
        return 
    end



	local app = sf.core.g_Application			
	local window = sf.gui.CWindow()
	window.Load(
		app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), window_id, true), 
		app.GetSettings().GetChild(_T("GUITemplates"), false))
	window.UpdateLayout()
	MoveWindowToCenter(_owner, window)

    if _window_type == "new" then
        local edit_widget = __cast(window.GetWidget(_T("edit")).get(), "sf.gui.CEditWidget")
        edit_widget.SetText(sf.misc.g_StringTable.Instance().FormatByStringsID(user_profiles.new_player_string_id))
        window.SetChildFocused(edit_widget)
        edit_widget.SelectText(0, edit_widget.GetText().size())
        profile_edit_window_dialog.TestEmptyName(window )
        if _disable_cancel then
            local cancel_button = __cast(window.GetWidget("cancel").get(), "sf.gui.CButtonWidget")
            cancel_button.DisableButton(true)
        end
    elseif _window_type == "rename" then
        local list_widget = __cast(_owner.GetWidget(_T("profiles_list")).get(), "sf.gui.CListWidget")
        local selected_profile_name = list_widget.GetLine(current_line)
        local edit_widget = __cast(window.GetWidget(_T("edit")).get(), "sf.gui.CEditWidget")
        window.SetChildFocused(edit_widget)

        edit_widget.SetText(selected_profile_name)
        profile_edit_window_dialog.TestEmptyName(window )
    else
        return
    end

	local window_ptr = sf.gui.CBaseWindowPtrT(window)
	local modal_res = _owner.DoModal(window_ptr)
	window_ptr = nil
	collectgarbage()

	return 	modal_res
end

function user_profiles.create_new_profile(_owner, _disable_cancel)
    local modal_res = user_profiles.run_modify_name_dialog(_owner, "new", _disable_cancel)

    if modal_res == 1 then
        main_menu.init_welcome(_owner.GetParentWindow())
        game.g_ProfileManager.Instance().Save()
        game.g_GameOptions.Instance().ApplyOptionsChanges()
        _owner.EndModal(1)
    elseif modal_res == 0 then
    end
end

function user_profiles.change_player_dialog_script(_owner, _action, _child)
	local app = sf.core.g_Application
	local list_widget = __cast(_owner.GetWidget(_T("profiles_list")).get(), "sf.gui.CListWidget")
	if _child.GetId()==_T("profiles_list") and _action==_T("line_selected") then
--[[		
		current_line = list_widget.GetSelectedLine()
		if current_line ~= -1 then
			game.g_ProfileManager.Instance().SetCurrentProfile(list_widget.GetLine(current_line))
			main_menu.init_welcome(_owner.GetParentWindow())
		else
		end
	]]	
	elseif _child.GetId()==_T("ok") and _action==_T("pressed") or _action == _T("key_down_enter") then

    	local list_widget = __cast(_owner.GetWidget(_T("profiles_list")).get(), "sf.gui.CListWidget")
		
		current_line = list_widget.GetSelectedLine()
		if current_line ~= -1 then
			game.g_ProfileManager.Instance().SetCurrentProfile(list_widget.GetLine(current_line))
			main_menu.init_welcome(_owner.GetParentWindow())
		else
		end

		game.g_ProfileManager.Instance().Save()
		game.g_GameOptions.Instance().ApplyOptionsChanges()
		_owner.EndModal(1)
	elseif _child.GetId()==_T("new") and _action==_T("pressed")  then
        user_profiles.create_new_profile(_owner)	
	elseif _child.GetId()==_T("cancel") and _action==_T("pressed") or _action == _T("key_down_escape") then
		if user_profiles.temp_profile ~= _T("") then
			local old_profile = game.g_ProfileManager.Instance().GetProfile(user_profiles.temp_profile)
			if old_profile ~= nil then
				game.g_ProfileManager.Instance().SetCurrentProfile(user_profiles.temp_profile)
				main_menu.init_welcome(_owner.GetParentWindow())
			end
		end
		_owner.EndModal(0)
	elseif _child.GetId()==_T("delete") and _action==_T("pressed") then
			num_lines = list_widget.EnumLines()
			current_line = list_widget.GetSelectedLine()
			if num_lines > 0 and current_line ~= -1 then
				if user_profiles.run_delete_user_name_dialog(_owner, list_widget.GetLine(current_line)) == 1 then
					local profile_name = game.g_ProfileManager.Instance().DeleteProfile(list_widget.GetLine(current_line))
					local num_of_profiles = game.g_ProfileManager.Instance().EnumProfiles()
					if num_of_profiles > 0 then
						game.g_ProfileManager.Instance().SetCurrentProfile(0)
					end
					user_profiles.update_list_with_profiles(list_widget)
					main_menu.init_welcome(_owner.GetParentWindow())				
					game.g_ProfileManager.Instance().Save()
				end
                if list_widget.EnumLines() == 0 then
                   user_profiles.create_new_profile(_owner, true)	 
                end
			end
	elseif _child.GetId()==_T("rename") and _action==_T("pressed") then
		num_lines = list_widget.EnumLines()
		current_line = list_widget.GetSelectedLine()
		if num_lines > 0 and current_line ~= -1 then
			list_widget.GetLine(current_line)
            local modal_res = user_profiles.run_modify_name_dialog(_owner, "rename")

			if modal_res == 1 then
				local list_widget = __cast(_owner.GetWidget(_T("profiles_list")).get(), "sf.gui.CListWidget")
				if list_widget then
					user_profiles.update_list_with_profiles(list_widget)
				end
				main_menu.init_welcome(_owner.GetParentWindow())
				game.g_ProfileManager.Instance().Save()
			elseif modal_res == 0 then
			end
		else
		end
	end
end

function user_profiles.update_list_with_profiles(_list_widget)
	
	_list_widget.ClearLines()
	
	local num_profiles = game.g_ProfileManager.Instance().EnumProfiles()
	if num_profiles > 0 then
		local current_profile_name = _T("")
		local current_profile = game.g_ProfileManager.Instance().GetCurrentProfile()
		if current_profile ~= nil then
			current_profile_name = current_profile.GetName()
		end
	
		local i = 0
		local current_profile_id = -1
		while i ~= num_profiles do 
			local new_line_id = game.g_ProfileManager.Instance().GetProfile(i).GetName()
			if new_line_id == current_profile_name then
				current_profile_id = i
			end
			_list_widget.AddLine(new_line_id)
			i = i + 1
		end
		_list_widget.SelectLine(current_profile_id, false)
	else
	end
	
end

function user_profiles.run_delete_user_name_dialog(_owner, _user_name)
    local app = sf.core.g_Application
	local window = sf.gui.CWindow()
	window.Load(
	app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), _T("s10_user_delete_profile"), true), 
		app.GetSettings().GetChild(_T("GUITemplates"), false))
														    
	local label_widget = __cast(window.GetWidget(_T("delete_message_label")).get(), "sf.gui.CLabelWidget")
	
	local template_text = label_widget.GetText()
	
	local new_text = qe.StringFormat(template_text, _user_name)
	
	label_widget.SetText(new_text)
	
	
	window.UpdateLayout()                                             
	MoveWindowToCenter(_owner, window)
	local window_ptr = sf.gui.CBaseWindowPtrT(window)
	local modal_res = _owner.DoModal(window_ptr)
	window_ptr = nil
	collectgarbage()
	return modal_res
end



function user_profiles.run_dialog(_owner, _window_type)

    local window_id = _T("")
    if _window_type == "empty" then
        window_id = _T("s10_user_empty_user_name")
    elseif _window_type == "dublicate" then
        window_id = _T("s10_user_dublicate_profile")
    else
        return 
    end
    local app = sf.core.g_Application
	local window_group = app.GetSettings().GetChild(_T("GUI"), false).GetChildByAttribute(_T("window"), _T("id"), window_id, true)
    if window_group.GetId() ~= _T("") then
        
        local window = sf.gui.CWindow()
        window.Load(window_group, app.GetSettings().GetChild(_T("GUITemplates"), false)	)
        window.UpdateLayout()                                             
        MoveWindowToCenter(_owner, window)
        local window_ptr = sf.gui.CBaseWindowPtrT(window)
        _owner.DoModal(window_ptr)
        window_ptr = nil
        collectgarbage()
    else
        __message("Невозможно загрузить окно с сообщением о пустом имени пользователя", "")
    end
end