-- модуль отвечающий за работу системы окон профайлов
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.ok_child = 
{
	pressed = function(_window) 
		_owner.AddFlags(_owner.FlagDead)
	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)
	profile_edit_window_dialog._UpdateClips()
end

function profile_edit_window_dialog.TestEmptyName(_this )
    local edit_widget = _this.GetWidget("edit").get()
    if edit_widget then
        edit_widget = __cast(edit_widget, sf.gui.CEditWidget)
        if edit_widget then
            local edit_text = edit_widget.GetText()
            profile_edit_window_dialog._can_modify = (edit_text.c_str() ~= "")
			if profile_edit_window_dialog._can_modify then
				profile_edit_window_dialog._can_modify = not s11.IsAllSpaces(edit_text)
			end
			
            local button_widget = _this.GetWidget("ok_modify").get()
            button_widget = __cast(button_widget, sf.gui.CButtonWidget)
            if button_widget then
				button_widget.DisableButton(not profile_edit_window_dialog._can_modify)
            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.SuperOnKeyDown( _key, _keyboard_state, _state, _broadcast) and _key == 13 then
		_this.SetChildFocused(nil)
        return true
    end
	
	if _key == 13 or _key == 27 then
	    if (_this.GetId().c_str() == "s11_new_user" or _this.GetId().c_str() == "s11_rename_user") then
			if _key == 13 and profile_edit_window_dialog._can_modify then
				user_profiles.run_modify_function(_this)
			elseif _key == 27 and profile_edit_window_dialog._can_cancel then
				_this.EndModal(0)
			end
		else
			_this.EndModal(1)
	    end	
		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)
	
	local man_over = profile_edit_window_dialog._man_clip.GetPoly().IsContains(_pos.X, _pos.Y) and 
						not __IsTransparentPoint(profile_edit_window_dialog._man_texture, 
								_pos.X - profile_edit_window_dialog._man_image_offset.X, 
								_pos.Y - profile_edit_window_dialog._man_image_offset.Y)
	
	local woman_over = profile_edit_window_dialog._woman_clip.GetPoly().IsContains(_pos.X, _pos.Y) and 
						not __IsTransparentPoint(profile_edit_window_dialog._woman_texture, 
							_pos.X - profile_edit_window_dialog._woman_image_offset.X, 
							_pos.Y - profile_edit_window_dialog._woman_image_offset.Y)
	
	__visible(profile_edit_window_dialog._man_glow_over_clip, man_over)
	__visible(profile_edit_window_dialog._woman_glow_over_clip, woman_over)
	
	if man_over or woman_over then
		sf.gui.g_Cursor.Instance().SetCursor(sf.gui.CCursor.CursorHand)
	end
	
	return _this.SuperOnMouseMove( _pos, _state, _broadcast) 
end

function profile_edit_window_dialog.OnMouseDown(_this, _pos, _button, _state, _broadcast)
	if _this.SuperOnMouseDown( _pos, _button, _state, _broadcast) then
		return true
	end
	if not _broadcast then
		
		local man_over = profile_edit_window_dialog._man_clip.GetPoly().IsContains(_pos.X, _pos.Y) and 
						not __IsTransparentPoint(profile_edit_window_dialog._man_texture, 
								_pos.X - profile_edit_window_dialog._man_image_offset.X, 
								_pos.Y - profile_edit_window_dialog._man_image_offset.Y)
	
		local woman_over = profile_edit_window_dialog._woman_clip.GetPoly().IsContains(_pos.X, _pos.Y) and 
						not __IsTransparentPoint(profile_edit_window_dialog._woman_texture, 
							_pos.X - profile_edit_window_dialog._woman_image_offset.X, 
							_pos.Y - profile_edit_window_dialog._woman_image_offset.Y)
							
		if profile_edit_window_dialog._man_clip.GetPoly().IsContains(_pos.X, _pos.Y) and man_over then
			profile_edit_window_dialog._is_female = false
			return true
		end
		
		if profile_edit_window_dialog._woman_clip.GetPoly().IsContains(_pos.X, _pos.Y) and woman_over then
			profile_edit_window_dialog._is_female = true
			return true
		end
	end
	return false
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

function profile_edit_window_dialog.InitClips(_this, _is_female)
	profile_edit_window_dialog._man_clip = __cast(_this.GetWidget("man").get(), "sf.gui.CClipWidget")
	profile_edit_window_dialog._man_glow_clip = __cast(_this.GetWidget("man_glow").get(), "sf.gui.CClipWidget")
	profile_edit_window_dialog._man_glow_over_clip = __cast(_this.GetWidget("man_glow_over").get(), "sf.gui.CClipWidget")
	profile_edit_window_dialog._woman_clip = __cast(_this.GetWidget("woman").get(), "sf.gui.CClipWidget")
	profile_edit_window_dialog._woman_glow_clip = __cast(_this.GetWidget("woman_glow").get(), "sf.gui.CClipWidget")
	profile_edit_window_dialog._woman_glow_over_clip = __cast(_this.GetWidget("woman_glow_over").get(), "sf.gui.CClipWidget")
	
	assert(profile_edit_window_dialog._man_clip)
	assert(profile_edit_window_dialog._man_glow_clip)
	assert(profile_edit_window_dialog._man_glow_over_clip)
	assert(profile_edit_window_dialog._woman_clip)
	assert(profile_edit_window_dialog._woman_glow_clip)
	assert(profile_edit_window_dialog._woman_glow_over_clip)
	
	local man_image = profile_edit_window_dialog._man_clip.GetClip().FindObject("image screens_create_player_man 1")
	assert(man_image)
	local man_offset = profile_edit_window_dialog._man_clip.GetOffset()
	local man_image_center = man_image.GetPos()
	local man_image_poly = man_image.GetPoly()
	profile_edit_window_dialog._man_image_offset = sf.misc.FloatVector(
		man_offset.X + man_image_center.X + man_image_poly.Point(0).X, 
		man_offset.Y + man_image_center.Y + man_image_poly.Point(0).Y)
	
	local woman_image = profile_edit_window_dialog._woman_clip.GetClip().FindObject("image screens_create_player_woman 1")
	assert(woman_image)
	local woman_offset = profile_edit_window_dialog._woman_clip.GetOffset()	
	local woman_image_center = woman_image.GetPos()
	local woman_image_poly = woman_image.GetPoly()
	profile_edit_window_dialog._woman_image_offset = sf.misc.FloatVector(
		woman_offset.X + woman_image_center.X + woman_image_poly.Point(0).X, 
		woman_offset.Y + woman_image_center.Y + woman_image_poly.Point(0).Y)
	
	profile_edit_window_dialog._man_texture = sf.core.g_Application.GetResourceManager().GetTexture("screens_create_player_man")
	profile_edit_window_dialog._woman_texture = sf.core.g_Application.GetResourceManager().GetTexture("screens_create_player_woman")
	
	assert(profile_edit_window_dialog._man_texture)
	assert(profile_edit_window_dialog._woman_texture)
	
	profile_edit_window_dialog._is_female = _is_female
end

function profile_edit_window_dialog._UpdateClips()
	__visible(profile_edit_window_dialog._man_glow_clip, not profile_edit_window_dialog._is_female)
	__visible(profile_edit_window_dialog._woman_glow_clip, profile_edit_window_dialog._is_female)
end

user_profiles = {}
user_profiles.temp_profile = ""

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 = s11.COnKeyDownWindow()
    local window = sf.gui.CWindow()

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

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

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

	_owner.AddChildWindow(window)

end


function user_profiles.run_modify_function(_owner)
    if user_profiles.current_modify_window_type == "new" then
		local edit_widget = __cast(_owner.GetWidget("edit").get(), "sf.gui.CEditWidget")
		local edit_text = edit_widget.GetText()
		if edit_text.c_str() == "" then
            user_profiles.run_dialog(_owner, "empty")
		else
			local find_profile_res = s11.g_ProfileManager.Instance().GetProfile(edit_text)
			if find_profile_res and profile_edit_window_dialog._start_name ~= edit_text then
                    user_profiles.run_dialog(_owner, "dublicate")
			else
				local temp_text = std.wstring(edit_text)
				edit_text = s11.ReplaceDollarByS(edit_text);
				
				local profile = s11.g_ProfileManager.Instance().CreateProfile(edit_text, true)
				assert(profile)
				profile.SetFemale(profile_edit_window_dialog._is_female)
			
				local widget_ = _owner.GetParentWindow().GetWidget("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 = s11.g_ProfileManager.Instance().GetCurrentProfile()
		local profile_name = edited_profile.GetName()
		local widget_ = _owner.GetParentWindow().GetWidget("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("edit").get(), "sf.gui.CEditWidget")
		local edit_text = edit_widget.GetText()
		if edit_text.c_str() ~= "" then
			local current_profile = s11.g_ProfileManager.Instance().GetCurrentProfile()
			local find_profile_res = s11.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_dialog(_owner, "dublicate")
			else
					edit_text = s11.ReplaceDollarByS(edit_text);
					s11.g_ProfileManager.Instance().Rename(profile_name, edit_text)
					
					s11.g_ProfileManager.Instance().SetCurrentProfile(edit_text)
					local profile = s11.g_ProfileManager.Instance().GetCurrentProfile()
					assert(profile)					
					profile.SetFemale(profile_edit_window_dialog._is_female)
					if current_profile then
						s11.g_ProfileManager.Instance().SetCurrentProfile(current_profile.GetName())
					end
					_owner.EndModal(1)
			end
		else
            user_profiles.run_dialog(_owner, "empty")
		end
    else
        return
    end
end

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

    local window_id = ""
    if _window_type == "new" then
        window_id = "s11_new_user"
    elseif _window_type == "rename" then
        window_id = "s11_rename_user"
    else
        return 
    end

	local app = sf.core.g_Application			
	local window = sf.gui.CWindow()
	window.Load(
		app.GetSettings().GetChild("GUI", false).GetChildByAttribute("window", "id", window_id, true), 
		app.GetSettings().GetChild("GUITemplates", false))
	window.UpdateLayout()
	MoveWindowToCenter(_owner, window)	
	
    if _window_type == "new" then
		profile_edit_window_dialog._start_name = nil
        local edit_widget = __cast(window.GetWidget("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)
		
		local first_profile = (s11.g_ProfileManager.Instance().EnumProfiles()==0)
		profile_edit_window_dialog._can_cancel = not first_profile
		
		local button_cancel = __cast(window.GetWidget("cancel").get(), "sf.gui.CButtonWidget")
		assert(button_cancel)
		__visible(button_cancel, profile_edit_window_dialog._can_cancel)
		
		local profile_options = g_App.GetSettings().GetChild("Constants", false).GetChild("profile_options", false)
		local is_female = profile_options.GetValue("default_is_female").c_str() == "true"
		profile_edit_window_dialog.InitClips(window, is_female)
		
    elseif _window_type == "rename" then
        local list_widget = __cast(_owner.GetWidget("profiles_list").get(), "sf.gui.CListWidget")
        local selected_profile_name = list_widget.GetLine(current_line)
        local edit_widget = __cast(window.GetWidget("edit").get(), "sf.gui.CEditWidget")
        window.SetChildFocused(edit_widget)

        edit_widget.SetText(selected_profile_name)
		profile_edit_window_dialog._start_name = selected_profile_name
        profile_edit_window_dialog.TestEmptyName(window )
		
		local profile = s11.g_ProfileManager.Instance().GetProfile(selected_profile_name)
		assert(profile)
		profile_edit_window_dialog.InitClips(window, profile.IsFemale())
    else
        return
    end

	return 	dialog_do_modal(window, _owner)
end

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

    if modal_res == 1 then
        main_menu.init_welcome(_owner.GetParentWindow())
        s11.g_ProfileManager.Instance().Save()
		_owner.AddFlags(_owner.FlagDead)
    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("profiles_list").get(), "sf.gui.CListWidget")
	if _child.GetId() == "profiles_list" and _action == "line_selected" then
	elseif _child.GetId().c_str() == "ok" and _action.c_str() == "pressed" or _action.c_str() == "key_down_enter" then

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

		s11.g_ProfileManager.Instance().Save()
		_owner.AddFlags(_owner.FlagDead)
	elseif _child.GetId().c_str() == "new" and _action.c_str() == "pressed" then
        user_profiles.create_new_profile(_owner)	
	elseif _child.GetId().c_str() == "cancel" and _action.c_str() == "pressed" or _action.c_str() == "key_down_escape" then
		if user_profiles.temp_profile.c_str() ~= "" then
			local old_profile = s11.g_ProfileManager.Instance().GetProfile(user_profiles.temp_profile)
			if old_profile ~= nil then
				s11.g_ProfileManager.Instance().SetCurrentProfile(user_profiles.temp_profile)
				main_menu.init_welcome(_owner.GetParentWindow())
			end
		end
		_owner.AddFlags(_owner.FlagDead)
	elseif _child.GetId().c_str() == "delete" and _action.c_str() == "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 = s11.g_ProfileManager.Instance().DeleteProfile(list_widget.GetLine(current_line))
					local num_of_profiles = s11.g_ProfileManager.Instance().EnumProfiles()
					if num_of_profiles > 0 then
						s11.g_ProfileManager.Instance().SetCurrentProfile(0)
					end
					user_profiles.update_list_with_profiles(list_widget)
					main_menu.init_welcome(_owner.GetParentWindow())
					s11.g_ProfileManager.Instance().Save()
				end
                if list_widget.EnumLines() == 0 then
                   user_profiles.create_new_profile(_owner)	 
                end
			end
	elseif _child.GetId().c_str() == "rename" and _action.c_str() == "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("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())
				s11.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 = s11.g_ProfileManager.Instance().EnumProfiles()
	if num_profiles > 0 then
		local current_profile_name = ""
		local current_profile = s11.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 = s11.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("GUI", false).GetChildByAttribute("window", "id", "s11_user_delete_profile", true), 
		app.GetSettings().GetChild("GUITemplates", false))
														    
	local label_widget = __cast(window.GetWidget("delete_message_label").get(), "sf.gui.CLabelWidget")
	
	local template_text = label_widget.GetText()
	
	local new_text = s11.StringFormat(template_text, _user_name)
	
	label_widget.SetText(new_text)
	
	
	window.UpdateLayout()                                             
	return 	dialog_do_modal(window, _owner)
end

function user_profiles.run_dialog(_owner, _window_type)

    local window_id = ""
    if _window_type == "empty" then
        window_id = "s11_user_empty_user_name"
    elseif _window_type == "dublicate" then
        window_id = "s11_user_dublicate_profile"
    else
        return 
    end
    local app = sf.core.g_Application
	local window_group = app.GetSettings().GetChild("GUI", false).GetChildByAttribute("window", "id", window_id, true)
    if window_group.GetId().c_str() ~= "" then
        
        local window = sf.gui.CWindow()
        window.Load(window_group, app.GetSettings().GetChild("GUITemplates", false)	)
        window.UpdateLayout()                                             
        MoveWindowToCenter(_owner, window)
		_owner.AddChildWindow(window)
    else
        __message("        ", "")
    end
end
