/*
 * This file is part of the MicroPython project, http://micropython.org/
 *
 * The MIT License (MIT)
 *
 * Copyright (c) 2016 Scott Shawcroft
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include "shared-bindings/busio/SPI.h"
#include "py/mperrno.h"
#include "py/runtime.h"

#include "hpl_sercom_config.h"
#include "peripheral_clk_config.h"

#include "hal/include/hal_gpio.h"
#include "hal/include/hal_spi_m_sync.h"
#include "hal/include/hpl_spi_m_sync.h"

#include "peripherals.h"
#include "pins.h"
#include "shared_dma.h"

// Convert frequency to clock-speed-dependent value. Return 0 if out of range.
static uint8_t baudrate_to_baud_reg_value(const uint32_t baudrate) {
    uint32_t baud_reg_value = (uint32_t) (((float) PROTOTYPE_SERCOM_SPI_M_SYNC_CLOCK_FREQUENCY /
                                           (2 * baudrate)) + 0.5f);
    if (baud_reg_value > 0xff) {
        return 0;
    }
    return (uint8_t) baud_reg_value;
}

void common_hal_busio_spi_construct(busio_spi_obj_t *self,
        const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi,
        const mcu_pin_obj_t * miso) {
    Sercom* sercom = NULL;
    uint8_t sercom_index;
    uint32_t clock_pinmux = 0;
    bool mosi_none = mosi == mp_const_none;
    bool miso_none = miso == mp_const_none;
    uint32_t mosi_pinmux = 0;
    uint32_t miso_pinmux = 0;
    uint8_t clock_pad = 0;
    uint8_t mosi_pad = 0;
    uint8_t miso_pad = 0;
    uint8_t dopo = 255;
    for (int i = 0; i < NUM_SERCOMS_PER_PIN; i++) {
        Sercom* potential_sercom = clock->sercom[i].sercom;
        sercom_index = clock->sercom[i].index; // 2 for SERCOM2, etc.
        if (potential_sercom == NULL ||
        #if defined(MICROPY_HW_APA102_SCK) && defined(MICROPY_HW_APA102_MOSI) && !defined(CIRCUITPY_BITBANG_APA102)
            (potential_sercom->SPI.CTRLA.bit.ENABLE != 0 &&
             potential_sercom != status_apa102.spi_master_instance.hw &&
             !apa102_sck_in_use)) {
        #else
            potential_sercom->SPI.CTRLA.bit.ENABLE != 0) {
        #endif
            continue;
        }
        clock_pinmux = PINMUX(clock->pin, (i == 0) ? MUX_C : MUX_D);
        clock_pad = clock->sercom[i].pad;
        if (!samd_peripheral_valid_spi_clock_pad(clock_pad)) {
            continue;
        }
        for (int j = 0; j < NUM_SERCOMS_PER_PIN; j++) {
            if (!mosi_none) {
                if(potential_sercom == mosi->sercom[j].sercom) {
                    mosi_pinmux = PINMUX(mosi->pin, (j == 0) ? MUX_C : MUX_D);
                    mosi_pad = mosi->sercom[j].pad;
                    dopo = samd_peripheral_get_spi_dopo(clock_pad, mosi_pad);
                    if (dopo > 0x3) {
                        continue;  // pad combination not possible
                    }
                    if (miso_none) {
                        sercom = potential_sercom;
                        break;
                    }
                } else {
                    continue;
                }
            }
            if (!miso_none) {
                for (int k = 0; k < NUM_SERCOMS_PER_PIN; k++) {
                    if (potential_sercom == miso->sercom[k].sercom) {
                        miso_pinmux = PINMUX(miso->pin, (k == 0) ? MUX_C : MUX_D);
                        miso_pad = miso->sercom[k].pad;
                        sercom = potential_sercom;
                        break;
                    }
                }
            }
            if (sercom != NULL) {
                break;
            }
        }
        if (sercom != NULL) {
            break;
        }
    }
    if (sercom == NULL) {
        mp_raise_ValueError("Invalid pins");
    }

    // Set up SPI clocks on SERCOM.
    samd_peripheral_sercom_clock_init(sercom, sercom_index);
    
    if (spi_m_sync_init(&self->spi_desc, sercom) != ERR_NONE) {
        mp_raise_OSError(MP_EIO);
    }
    
    hri_sercomspi_write_CTRLA_DOPO_bf(sercom, dopo);
    hri_sercomspi_write_CTRLA_DIPO_bf(sercom, miso_pad);

    // Always start at 250khz which is what SD cards need. They are sensitive to
    // SPI bus noise before they are put into SPI mode.
    uint8_t baud_value = baudrate_to_baud_reg_value(250000);
    if (baud_value == 0) {
        mp_raise_RuntimeError("SPI initial baudrate out of range.");
    }
    if (spi_m_sync_set_baudrate(&self->spi_desc, baud_value) != ERR_NONE) {
        // spi_m_sync_set_baudrate does not check for validity, just whether the device is
        // busy or not
        mp_raise_OSError(MP_EIO);
    }
        
    gpio_set_pin_pull_mode(clock->pin, GPIO_PULL_OFF);
    gpio_set_pin_function(clock->pin, clock_pinmux);
    claim_pin(clock);
    self->clock_pin = clock->pin;

    if (mosi_none) {
        self->MOSI_pin = NO_PIN;
    } else {
        gpio_set_pin_pull_mode(mosi->pin, GPIO_PULL_OFF);
        gpio_set_pin_function(mosi->pin, mosi_pinmux);
        self->MOSI_pin = mosi->pin;
        claim_pin(mosi);
    }

    if (miso_none) {
        self->MISO_pin = NO_PIN;
    } else {
        gpio_set_pin_pull_mode(miso->pin, GPIO_PULL_OFF);
        gpio_set_pin_function(miso->pin, miso_pinmux);
        self->MISO_pin = miso->pin;
        claim_pin(miso);
    }

    spi_m_sync_enable(&self->spi_desc);
}

bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) {
    return self->clock_pin == NO_PIN;
}

void common_hal_busio_spi_deinit(busio_spi_obj_t *self) {
    if (common_hal_busio_spi_deinited(self)) {
        return;
    }
    spi_m_sync_disable(&self->spi_desc);
    spi_m_sync_deinit(&self->spi_desc);
    reset_pin(self->clock_pin);
    reset_pin(self->MOSI_pin);
    reset_pin(self->MISO_pin);
    self->clock_pin = NO_PIN;
}

bool common_hal_busio_spi_configure(busio_spi_obj_t *self,
        uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) {
    uint8_t baud_reg_value = baudrate_to_baud_reg_value(baudrate);
    if (baud_reg_value == 0) {
        mp_raise_ValueError("baudrate out of range");
    }

    void * hw = self->spi_desc.dev.prvt;
    // If the settings are already what we want then don't reset them.
    if (hri_sercomspi_get_CTRLA_CPHA_bit(hw) == phase &&
        hri_sercomspi_get_CTRLA_CPOL_bit(hw) == polarity &&
        hri_sercomspi_read_CTRLB_CHSIZE_bf(hw) == ((uint32_t)bits - 8) &&
        hri_sercomspi_read_BAUD_BAUD_bf(hw) == baud_reg_value) {
        return true;
    }

    // Disable, set values (most or all are enable-protected), and re-enable. 
    spi_m_sync_disable(&self->spi_desc);
    hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK);

    hri_sercomspi_write_CTRLA_CPHA_bit(hw, phase);
    hri_sercomspi_write_CTRLA_CPOL_bit(hw, polarity);
    hri_sercomspi_write_CTRLB_CHSIZE_bf(hw, bits - 8);
    hri_sercomspi_write_BAUD_BAUD_bf(hw, baud_reg_value);
    hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK);

    spi_m_sync_enable(&self->spi_desc);
    hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK);

    return true;
}

bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) {
    bool grabbed_lock = false;
    CRITICAL_SECTION_ENTER()
        if (!self->has_lock) {
            grabbed_lock = true;
            self->has_lock = true;
        }
    CRITICAL_SECTION_LEAVE();
    return grabbed_lock;
}

bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) {
    return self->has_lock;
}

void common_hal_busio_spi_unlock(busio_spi_obj_t *self) {
    self->has_lock = false;
}

bool common_hal_busio_spi_write(busio_spi_obj_t *self,
        const uint8_t *data, size_t len) {
    if (len == 0) {
        return true;
    }
    int32_t status;
//    if (len >= 16) {
//        status = shared_dma_write(self->spi_desc.dev.prvt, data, len);
//    } else {
        struct io_descriptor *spi_io;
        spi_m_sync_get_io_descriptor(&self->spi_desc, &spi_io);
        status = spi_io->write(spi_io, data, len);
//    }
        return status > 0; // Status is number of chars read or an error code < 0.
}

bool common_hal_busio_spi_read(busio_spi_obj_t *self,
        uint8_t *data, size_t len, uint8_t write_value) {
    if (len == 0) {
        return true;
    }
    int32_t status;
//    if (len >= 16) {
//        status = shared_dma_read(self->spi_desc.dev.prvt, data, len, write_value);
//    } else {
        self->spi_desc.dev.dummy_byte = write_value;

        struct io_descriptor *spi_io;
        spi_m_sync_get_io_descriptor(&self->spi_desc, &spi_io);

        status = spi_io->read(spi_io, data, len);
//    }
        return status > 0; // Status is number of chars read or an error code < 0.
}
