%%%-------------------------------------------------------------------
%%% @author licheng5
%%% @copyright (C) 2023, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 14. 2月 2023 20:32
%%%-------------------------------------------------------------------
-module(iot_mock).
-author("licheng5").
-include("iot.hrl").

%% API
-export([rsa_encode/1]).
-export([insert_services/1]).
-export([test_mqtt/0, test_influxdb/0]).

test_influxdb() ->
    UUID = <<"device123123">>,

    lists:foreach(fun(Id) ->
        Point = influx_point:new(<<"shui_biao">>,
            [{<<"uuid">>, UUID}, {<<"service_name">>, <<"shui_biao">>}],
            [{<<"cost">>, Id}],
            iot_util:timestamp()),

        poolboy:transaction(influx_pool, fun(Pid) ->
           influx_client:write(Pid, <<"iot">>, <<"iot">>, [Point])
                                         end)
                  end, lists:seq(1, 100)).

test_mqtt() ->
    iot_zd_endpoint:forward(<<"location_code_test123">>, <<"location_code_test123">>, [
        #{<<"key">> => <<"name">>, <<"value">> => <<"anlicheng">>},
        #{<<"key">> => <<"age">>, <<"value">> => 30},
        #{<<"key">> => <<"flow">>, <<"value">> => 30}
    ], iot_util:timestamp_of_seconds()).

insert_services(Num) ->
    lists:foreach(fun(Id) ->
        Res = mysql_pool:insert(mysql_iot, <<"micro_service">>,
            #{
                <<"name">> => <<"微服务"/utf8, (integer_to_binary(Id))/binary>>,
                <<"code">> => <<"1223423423423423"/utf8>>,
                <<"type">> => 1,
                <<"version">> => <<"v1.0">>,
                <<"url">> => <<"https://www.baidu.com">>,
                <<"detail">> => <<"这是一个关于测试的微服务"/utf8>>
            }, false),
        lager:debug("insert service result is: ~p", [Res])
                  end, lists:seq(1, Num)).

rsa_encode(Data) when is_binary(Data) ->
    %% 读取相关配置
    PublicPemFile = "/tmp/keys/public.pem",

    %% 私钥保存解析后的
    {ok, PubBin} = file:read_file(PublicPemFile),
    lager:debug("pub bin is: ~p", [PubBin]),
    [Pub] = public_key:pem_decode(PubBin),
    lager:debug("pub pem bin is: ~p", [Pub]),
    PubKey = public_key:pem_entry_decode(Pub),
    lager:debug("the public key is: ~p", [PubKey]),

    EncData = public_key:encrypt_public(Data, PubKey),
    lager:debug("enc data is: ~p", [EncData]),

    rsa_decode(EncData),

    ok.

rsa_decode(EncData) when is_binary(EncData) ->
    %% 读取相关配置
    PublicPemFile = "/tmp/keys/pri.pem",

    %% 私钥保存解析后的
    {ok, PubBin} = file:read_file(PublicPemFile),
    lager:debug("pub bin is: ~p", [PubBin]),
    [Pub] = public_key:pem_decode(PubBin),
    lager:debug("pub pem bin is: ~p", [Pub]),
    PubKey = public_key:pem_entry_decode(Pub),
    lager:debug("the public key is: ~p", [PubKey]),

    PlainData = public_key:decrypt_private(EncData, PubKey),
    lager:debug("plain data is: ~p", [PlainData]),

    ok.