/*
Copyright (c) 2018 PHYTEC America, LLC.

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 <gpiod.h>
#include <stdio.h>

#include "board.h"
#include "common.h"
#include "c_gpio.h"

static const char *caller = "PHYTEC RPi.GPIO";
static struct gpiod_chip *chips[BOARD_GPIO_BANKS] = { NULL };

// grabs line associated with the values in board_pin and populates
// line_ptr with its address. returns 0 on success, -1 on failure
static int get_line(int bcm_pin, struct gpiod_line **line_ptr)
{
	unsigned int bank;
	const struct board_pin *board_pin;
	struct gpiod_chip *chip;
	struct gpiod_line *line;
	unsigned int pin;
	int ret;

	ret = bcm_to_board_pin(bcm_pin, &board_pin);
	if (ret) {
		fprintf(stderr, "%s: BCM pin is not valid for this board!\n",
			__func__);

		return ret;
	}

	bank = (unsigned int)board_pin->bank - GPIO_BANK_OFFSET;
	pin = (unsigned int)board_pin->pin;

	if (!chips[bank]) {
		chip = gpiod_chip_open_by_number(bank);

		if (!chip) {
			fprintf(stderr,
				"%s: gpiod_chip_open_by_number failed\n",
				__func__);

			return -1;
		}

		chips[bank] = chip;
	} else {
		chip = chips[bank];
	}

	line = gpiod_chip_get_line(chip, pin);
	if (!line) {
		fprintf(stderr, "%s: gpiod_chip_get_line failed\n", __func__);
		gpiod_chip_close(chip);

		return -1;
	}

	*line_ptr = line;

	return 0;
}

// iterates through all GPIO chips and closes them, releasing all associated
// GPIOs
void cleanup(void)
{
	int i;

	for (i = 0; i < BOARD_GPIO_BANKS; i++) {
		if (chips[i]) {
			gpiod_chip_close(chips[i]);
			chips[i] = NULL;
		}
	}
}

// returns gpio direction of bcm_pin. returns 1 for input, 2 for output,
// and -1 on error
int gpio_direction(int bcm_pin)
{
	struct gpiod_line *line;
	int ret;

	ret = get_line(bcm_pin, &line);
	if (ret) {
		fprintf(stderr, "%s: get_chip_and_line failed\n", __func__);
		return -1;
	}

	if (!gpiod_line_is_requested(line)) {
		fprintf(stderr, "%s: this line hasn't been configured!\n",
			__func__);
		return -1;
	}

	return gpiod_line_direction(line);
}

// retrieve input value from bcm_pin. returns negative value on error
int input_gpio(int bcm_pin)
{
	struct gpiod_line *line;
	int ret;

	ret = get_line(bcm_pin, &line);
	if (ret) {
		fprintf(stderr, "%s: get_chip_and_line failed\n", __func__);
		return ret;
	}

	ret = gpiod_line_get_value(line);
	if (ret < 0)
		fprintf(stderr, "%s: gpiod_line_get_value failed\n", __func__);

	return ret;
}

// sets bcm_pin to value. returns 0 on success, negative value on error
int output_gpio(int bcm_pin, int value)
{
	struct gpiod_line *line;
	int ret;

	ret = get_line(bcm_pin, &line);
	if (ret) {
		fprintf(stderr, "%s: get_chip_and_line failed\n", __func__);
		return ret;
	}

	ret = gpiod_line_set_value(line, value);
	if (ret)
		fprintf(stderr, "%s: gpiod_line_set_value failed\n", __func__);

	return ret;
}

// releases GPIO associated with bcm_pin for use by other programs. returns 0
// on success or negative value on error
int cleanup_gpio(int bcm_pin)
{
	struct gpiod_line *line;
	int ret;

	ret = get_line(bcm_pin, &line);
	if (ret) {
		fprintf(stderr, "%s: get_line failed\n", __func__);
		return ret;
	}

	if (gpiod_line_is_requested(line))
		gpiod_line_release(line);

	return 0;
}

// reserves and configures gpio associated with bcm_pin. takes direction
// (INPUT or OUTPUT) and initial value. returns 0 on success, negative value
// on error
int setup_gpio(int bcm_pin, int dir, int value)
{
	struct gpiod_line *line;
	int ret;

	ret = get_line(bcm_pin, &line);
	if (ret) {
		fprintf(stderr, "%s: get_line failed\n", __func__);
		return ret;
	}

	if (gpiod_line_is_requested(line)) {
		if (gpiod_line_direction(line) != dir)
			gpiod_line_release(line);
		else
			if (dir == OUTPUT) {
				ret = gpiod_line_set_value(line, value);
				goto exit;
			}
	}

	if (dir == OUTPUT) {
		ret = gpiod_line_request_output(line, caller, value);
	} else { /* dir == INPUT */
		ret = gpiod_line_request_input(line, caller);
	}

exit:
	if (ret)
		fprintf(stderr, "%s: gpiod_line_request failed\n", __func__);

	return ret;
}