/* Blink Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "sdkconfig.h"
#include "esp_mac.h"
#include <string.h>

#include "components/radio.h"
#include "components/sensors.h"
#include "components/util.h"
#include "hw/bme680b.h"
#include "hw/ccs811.h"
#include "hw/i2cbrn.h"
#include "hw/ina260.h"
#include "hw/mcp23018.h"
#include "hw/mpu9250.h"
#include "hw/buscfg.h"
#include "components/sdcard.h"

#include "hw/gps.h"

#define TAG "cantest"

void app_main(void)
{

    ESP_LOGI("BOOT", "BRN Systems incorporated CanSat flight firmware build at %s %s", __DATE__, __TIME__);

    /* instantiate i2c master bus 0 */
    ESP_ERROR_CHECK_WITHOUT_ABORT(i2c_new_master_bus(&i2c0_bus_cfg, &i2c0_bus_hdl));

    // spi_bus_config_t MCPBusCfg = {
    //     .mosi_io_num = -1,
    //     .miso_io_num = MCP3550_MISO_GPIO,
    //     .sclk_io_num = MCP3550_SCK_GPIO,
    //     .quadwp_io_num = -1,
    //     .quadhd_io_num = -1,
    //     .max_transfer_sz = 4,
    // };
    // ESP_ERROR_CHECK_WITHOUT_ABORT(spi_bus_initialize(SPI2_HOST, &MCPBusCfg, SPI_DMA_DISABLED));

    gpio_pullup_en(HSPI_MISO_GPIO);
    gpio_pullup_en(HSPI_SD_CS);
    spi_bus_config_t HighSpeedBusCfg = {
        // CONNECTED to LoRa and SD card
        .mosi_io_num = HSPI_MOSI_GPIO,
        .miso_io_num = HSPI_MISO_GPIO,
        .sclk_io_num = HSPI_SCK_GPIO,
        .quadwp_io_num = -1,
        .quadhd_io_num = -1,
        .max_transfer_sz = 64, // probably change
    };
    ESP_ERROR_CHECK_WITHOUT_ABORT(spi_bus_initialize(SPI3_HOST, &HighSpeedBusCfg, SPI_DMA_CH_AUTO));

    /* scan i2c devices on i2c master bus 0 and print results */
    ESP_ERROR_CHECK_WITHOUT_ABORT(i2c_master_bus_detect_devices(i2c0_bus_hdl));

    mcp23018_init();

    initSD();

    void servoControllerInit();

    ESP_LOGI(TAG, "BEGIN ESP TASKS");

    /* create task pinned to the app core */
    xTaskCreate(
        i2c_sensors_task,
        "I2CTaskBME",
        8192,
        NULL,
        (tskIDLE_PRIORITY + 2),
        NULL);

    xTaskCreate(
        lora_comms_task,
        "LoraCommsTask",
        8192,
        NULL,
        (tskIDLE_PRIORITY + 2),
        NULL);

    xTaskCreate(
        gps_task,
        "gps_task",
        8192,
        NULL,
        (tskIDLE_PRIORITY + 2),
        NULL);

    while (1)
    {

        vTaskDelay(100 / portTICK_PERIOD_MS);
    }
}