\ExplSyntaxOn

\tl_set:Nn\l_pgfgo_territory_pattern_tl{north~west~lines}
\tl_set:Nn\l_pgfgo_territory_line_color_tl{black}
\tl_set:Nn\l_pgfgo_territory_line_opacity_tl{1}
\tl_set:Nn\l_pgfgo_territory_fill_color_tl{black}
\tl_set:Nn\l_pgfgo_territory_fill_opacity_tl{1}

\keys_define:nn{ pgfgo / territory}{
	forget						.code:n	=	{\bool_set_false:N\l_pgfgo_goban_remember_territory_bool},
	forget						.groups:n	=	{preset},

	remember					.code:n	=	{\bool_set_true:N\l_pgfgo_goban_remember_territory_bool},
	remember					.groups:n	=	{preset},

	pattern				.tl_set:N = \l_pgf_territory_pattern_tl,

	black			.code:n			= {
		\bool_set_true:N\l_pgfgo_territory_player_black_bool
		\bool_set_false:N\l_pgfgo_territory_player_white_bool
		\keys_set:nn{ pgfgo / territory }{
			line~color = \l_pgfgo_player_black_line_color_tl,
			fill~color = \l_pgfgo_player_black_fill_color_tl,
		}
	},
	b 				.code:n = {\keys_set:nn {pgfgo / territory} {black}},
	

	white			.code:n			= {
		\bool_set_false:N\l_pgfgo_territory_player_black_bool
		\bool_set_true:N\l_pgfgo_territory_player_white_bool
		\keys_set:nn{ pgfgo / territory }{
			line~color = \l_pgfgo_player_white_line_color_tl,
			fill~color = \l_pgfgo_player_white_fill_color_tl,
		}
	},
	w 				.code:n = {\keys_set:nn {pgfgo / territory} {white}},

	neutral		.code:n			= {
		\bool_set_false:N\l_pgfgo_territory_player_black_bool
		\bool_set_false:N\l_pgfgo_territory_player_white_bool
		\keys_set:nn{ pgfgo / territory }{
			line~color = \l_pgfgo_player_neutral_line_color_tl,
			fill~color = \l_pgfgo_player_neutral_fill_color_tl,
		}
	},

	line~color			.tl_set:N = \l_pgfgo_territory_line_color_tl,

	line~opacity		.tl_set:N = \l_pgfgo_territory_line_opacity_tl,

	fill~color			.tl_set:N = \l_pgfgo_territory_fill_color_tl,

	fill~opacity		.tl_set:N = \l_pgfgo_territory_fill_opacity_tl,
}



\cs_set_protected:Npn\pgfgo_territory:nn #1#2 {
	\group_begin:

	\keys_set:nn{pgfgo / territory} {#1}

	\pgfonlayer{pgfgo_layer_territory}
	\clist_set:Nx\l_pgfgo_territory_coordinates_clist{#2}

	\clist_pop:NN\l_pgfgo_territory_coordinates_clist\l_pgfgo_territory_first_coordinate_tl
	\pgfgo_parse_coordinate:V\l_pgfgo_territory_first_coordinate_tl
	\pgfpathmoveto{\pgfpointxy{\l_pgfgo_parsed_x_coordinate_tl}{\l_pgfgo_parsed_y_coordinate_tl}}

	\clist_map_inline:Nn\l_pgfgo_territory_coordinates_clist{
		\pgfgo_parse_coordinate:n {##1}
		\pgfpathlineto{\pgfpointxy{\l_pgfgo_parsed_x_coordinate_tl}{\l_pgfgo_parsed_y_coordinate_tl}}
	}

	\pgfpathclose

	\pgfsetfillpattern{north~west~lines}{\l_pgfgo_territory_fill_color_tl}
	\pgfusepath{fill}
	\endpgfonlayer
	\group_end:
}



\DeclareDocumentCommand{\territory}{O{}m}{
	\keys_set_groups:nnn {pgfgo / territory} {preset} {#1}
	\bool_if:NT\l_pgfgo_goban_remember_territory_bool{
		\tl_gput_right:Nn\l_pgfgo_goban_elements_stack_tl{\pgfgo_territory:nn {#1}{#2}}
	}
	\pgfgo_territory:nn {#1}{#2}
}


\ExplSyntaxOff