/*
 * UPIWIN - Micro Pi Windowing Framework Kernel
 * Copyright (C) 2019 Amy Bowersox/Erbosoft Metaverse Design Solutions
 *    
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *    
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 *-------------------------------------------------------------------------
 */
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include "scode.h"
#include "log.h"
#include "gpio.h"
#include "ep_upiwin.h"
#include "ep_init.h"

PyObject *Epython_get_backlight(PyObject *self, PyObject *args)
{
  PUPIWIN_STATE pstate;
  
  if (!PyArg_ParseTuple(args, ""))
    return NULL;
  pstate = (PUPIWIN_STATE)PyModule_GetState(UPIWIN_module);
  return PyBool_FromLong((long)(pstate->backlight_on));
}

PyObject *Epython_set_backlight(PyObject *self, PyObject *args)
{
  PUPIWIN_STATE pstate;
  int new_state;

  if (!PyArg_ParseTuple(args, "p", &new_state))
    return NULL;
  pstate = (PUPIWIN_STATE)PyModule_GetState(UPIWIN_module);
  if (new_state && !(pstate->backlight_on))
    Gpio_set_backlight(pstate->backlight_level);
  else if (!new_state && pstate->backlight_on)
    Gpio_set_backlight(0);
  pstate->backlight_on = MAKEBOOL(new_state);
  return PyLong_FromUnsignedLong(S_OK);
}

PyObject *Epython_get_backlight_level(PyObject *self, PyObject *args)
{
  PUPIWIN_STATE pstate;
  
  if (!PyArg_ParseTuple(args, ""))
    return NULL;
  pstate = (PUPIWIN_STATE)PyModule_GetState(UPIWIN_module);
  return PyLong_FromUnsignedLong(pstate->backlight_level);
}

PyObject *Epython_set_backlight_level(PyObject *self, PyObject *args)
{
  PUPIWIN_STATE pstate;
  UINT32 new_level;
  HRESULT hr = S_OK;

  if (!PyArg_ParseTuple(args, "k", &new_level))
    return NULL;
  if (new_level <= GSB_BACKLIGHT_MAX)
  {
    pstate = (PUPIWIN_STATE)PyModule_GetState(UPIWIN_module);
    if (pstate->backlight_on)
      Gpio_set_backlight(new_level);
    pstate->backlight_level = new_level;
  }
  else
  {
    hr = E_INVALIDARG;
  }
  return PyLong_FromUnsignedLong(hr);
}
