#include <Arduino.h>
#include "abc800_gpio.h"
#include "abc800_keyboard.h"
static const char TAG[] = __FILE__;
extern portMUX_TYPE sync_isr;
extern TaskHandle_t Keyboard_ABC800_Task_In;

namespace abc800 {
    void IRAM_ATTR abc800keybord_rst_isr(){
        portENTER_CRITICAL(&sync_isr);
        if (!xTaskNotifyFromISR(Keyboard_ABC800_Task_In, ABC800_KEY_RESET, eSetValueWithoutOverwrite,NULL))
        {
            ESP_LOGE(TAG,"Could not notify task");
        }
        portEXIT_CRITICAL(&sync_isr);
    } 
    void IRAM_ATTR abc800keybord_kd_isr(){
        portENTER_CRITICAL(&sync_isr);
        Serial.println("x");
        if (!xTaskNotifyFromISR(Keyboard_ABC800_Task_In, ABC800_KEY_KD, eSetValueWithoutOverwrite,NULL))
        {
            ESP_LOGE(TAG,"Could not notify task");
        }
        portEXIT_CRITICAL(&sync_isr);
    } 
	void gpio::init(){
        uint8_t i;
        pinMode(KEY800_LED,OUTPUT);
        ledcSetup(KEY800_PWM_CHANNEL, KEY800_PWM_FREQ, KEY800_PWM_RES);
        pinMode(K800_RST ,INPUT);
        pinMode(A800_RST ,OUTPUT);
        digitalWrite(A800_RST,HIGH);
        pinMode(K800_TRXC ,INPUT);
        pinMode(A800_TRXC ,OUTPUT);
        pinMode(K800_KD ,INPUT);
        pinMode(A800_KD ,OUTPUT);
        pinMode(KEY800_MENU_BUTTON,INPUT);
        pinMode(KEY800_UP_BUTTON,INPUT);
        pinMode(KEY800_DOWN_BUTTON,INPUT);
        //Attach PWM
        ledcAttachPin(A800_TRXC, KEY800_PWM_CHANNEL);
        ledcWrite(KEY800_PWM_CHANNEL,KEY800_PWM_DUTY);
        
        //Serial2.begin(650,SERIAL_8N2,A800_RXD,A800_TXD);
        attachInterrupt(K800_RST,abc800keybord_rst_isr,CHANGE);
        attachInterrupt(K800_KD,abc800keybord_kd_isr,CHANGE);

    }
    uint8_t gpio::sendkey(uint8_t key){
        if (key!=0xff){
            ESP_LOGD(TAG,"OUT CODE %02x",key);
            digitalWrite(A800_KD, HIGH);
            Serial1.write(key);
            vTaskDelay( ABC800_KEY_DELAY_LEGACY);  // Enter needs longer delay so basic has enuff time to parse
            digitalWrite(A800_KD, LOW);
        }
        return 0;
    }
    uint8_t gpio::sendfunction(uint8_t key){
        if (key!=0xff){
            ESP_LOGD(TAG,"OUT CODE %02x",key);

            Serial1.write(key);
        }
        return 0;
    }
    uint8_t gpio::abc800_getupdown(){
        return (digitalRead(K800_KD));
    }
    uint8_t gpio::abc800_getkey(){
        uint8_t key=0;
        return key;
    }

}