%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2024, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 01. 8月 2024 11:17
%%%-------------------------------------------------------------------
-module(iot_queue).
-author("anlicheng").

%% API
-export([new/1, in/2, out/1, is_full/1, len/1]).

-record(iot_queue, {
    capacity = 1024,
    len = 0,
    queue = queue:new() :: queue:queue()
}).

-spec new(Capacity :: integer()) -> Q :: #iot_queue{}.
new(Capacity) when is_integer(Capacity) ->
    #iot_queue{
        capacity = Capacity,
        len = 0,
        queue = queue:new()
    }.

-spec is_full(Iot_queue :: #iot_queue{}) -> boolean().
is_full(#iot_queue{capacity = Capacity, len = Len}) ->
    Len >= Capacity.

-spec len(Iot_queue :: #iot_queue{}) -> integer().
len(#iot_queue{len = Len}) ->
    Len.

-spec in(Item :: any(), TQ :: #iot_queue{}) -> NQ :: #iot_queue{}.
in(_Item, TQ = #iot_queue{capacity = Capacity, len = Len}) when Len >= Capacity ->
    TQ;
in(Item, TQ = #iot_queue{queue = Q, len = Len}) ->
    TQ#iot_queue{
        queue = queue:in(Item, Q),
        len = Len + 1
    }.

-spec out(TQ :: #iot_queue{}) -> {{value, Item :: any()}, TQ1 :: #iot_queue{}} | {empty, TQ1 :: #iot_queue{}}.
out(TQ = #iot_queue{queue = Q, len = Len}) ->
    case queue:out(Q) of
        {{value, Item}, Q1} ->
            {{value, Item}, TQ#iot_queue{queue = Q1, len = Len - 1}};
        {empty, _} ->
            {empty, TQ}
    end.