#include "esphome/core/log.h"
#include "tuya_cover.h"

namespace esphome {
namespace tuya_cover {

bcm500ds driver;

static const char *TAG = "tuya_cover.cover";

void tuyaCover::setup() {
    ESP_LOGI(TAG, "TUYA_COVER_COMMAND = QUERY_STATUS");
    driver.setup();
}

void tuyaCover::loop() {

    driver.loop();

    bool have_message = driver.read();

    if(have_message && driver.query_cmd() == bcm500ds::TUYA_COVER_HEARTBEAT)
    {
        ESP_LOGI(TAG, "TUYA_COVER_RESPONSE = %s", (driver.query_value(0) == 0) ? "FIRST_HEARTBEAT" : "HEARTBEAT");  
    }
    else if (have_message && driver.query_cmd() == bcm500ds::TUYA_COVER_RESPONSE)
    {
        switch (driver.query_value(0))
        {
        case bcm500ds::TUYA_COVER_DPID_POSITION:
            ESP_LOGI(TAG, "TUYA_COVER_DPID_POSITION = %d%%", driver.query_value(7));
            this->position = driver.query_pos();
            this->publish_state();
            break;
        case bcm500ds::TUYA_COVER_DPID_DIRECTION:
            ESP_LOGI(TAG, "TUYA_COVER_DPID_DIRECTION = 0x%02X", driver.query_value(4));
            break;
        case bcm500ds::TUYA_COVER_DPID_UNKNOWN:
            ESP_LOGI(TAG, "TUYA_COVER_DPID_UNKNOWN ENUM = 0x%02X", driver.query_value(4));
            break;
        case bcm500ds::TUYA_COVER_DPID_ERROR:
            ESP_LOGI(TAG, "TUYA_COVER_DPID_ERROR BITMAP = 0x%02X", driver.query_value(4));
            break;
        default:
            break;
        }
    }
}

void tuyaCover::dump_config() {
    ESP_LOGCONFIG(TAG, "Tuya cover");
}

cover::CoverTraits tuyaCover::get_traits() {
    auto traits = cover::CoverTraits();
    traits.set_is_assumed_state(false);
    traits.set_supports_position(false);
    traits.set_supports_tilt(false);

    return traits;
}

void tuyaCover::control(const cover::CoverCall &call) {
    if (call.get_position().has_value())
        {
            // Write pos (range 0-1) to cover
            // Cover pos (range 0x00-0x64) (closed - open)
            uint8_t pos = (100-(*call.get_position() * 100));
            ESP_LOGV(TAG, "POS = %d", pos);

            switch (pos)
            {
            case 0:
                driver.command_close();
                break;
            case 100:
                driver.command_open();
                break;
            default:
                driver.command_gotoPos(pos);
                break;
            }
            // publish_state only when position is confirmed in loop()
        }
        if (call.get_stop())
        {
            // User requested cover stop
            driver.command_stop();
            ESP_LOGI(TAG, "TUYA_COVER_COMMAND = STOP");
        }
}

}  // namespace tuya_cover
}  // namespace esphome
