%% @doc Closes statement / portal
%%
%% ```
%% > Close
%% < CloseComplete
%% '''
-module(cloudi_x_epgsql_cmd_close).
-behaviour(cloudi_x_epgsql_command).
-export([init/1, execute/2, handle_message/4]).
-export_type([response/0]).

-type response() :: ok | {error, cloudi_x_epgsql:query_error()}.

-include("cloudi_x_epgsql.hrl").
-include("cloudi_x_epgsql_protocol.hrl").

-record(close,
        {type :: statement | portal,
         name :: iodata()}).

init({Type, Name}) ->
    #close{type = Type, name = Name}.

execute(Sock, #close{type = Type, name = Name} = St) ->
    Packets = [
       cloudi_x_epgsql_wire:encode_close(Type, Name),
       cloudi_x_epgsql_wire:encode_flush()
      ],
    {send_multi, Packets, Sock, St}.

handle_message(?CLOSE_COMPLETE, <<>>, Sock, _St) ->
    {finish, ok, ok, Sock};
handle_message(?ERROR, Error, _Sock, _State) ->
    {sync_required, {error, Error}};
handle_message(_, _, _, _) ->
    unknown.
