#pragma once

#include <DHT.h>
#include <HumiditySensor.h>
#include "TempSensor.h"

#define TEMP_POSITIVE PIN_B3
#define DHT_PIN PIN_B4

struct DhtValues {
    int temperature;
    int humidity;
};

class Dht22Sensor : public TempSensor, public HumiditySensor {
    DHT dht = DHT(DHT_PIN, DHT22);
    DhtValues values;

public:
    Dht22Sensor(short id) :
        TempSensor(id), HumiditySensor(id) {
    }

    void setup() override {
        pinMode(TEMP_POSITIVE, OUTPUT);
        digitalWrite(TEMP_POSITIVE, HIGH);
        dht.begin();
        delay(2000);
    }

    bool readTemp() override {
        float temp = dht.readTemperature();
        float humid = dht.readHumidity();
        bool success = !isnan(temp) && !isnan(humid);
        values.temperature = roundf(temp * 10);
        values.humidity = roundf(humid * 10);
        return success;
    }

    void sendValues(bool voltage) override {
        voltage ? sendTempAndVoltage(values.temperature) : sendTemp(values.temperature);
        delay(100);
        sendHumidity(values.humidity);
    }

    void turnOnSensor() override {
        pinMode(DHT_PIN, INPUT_PULLUP);
        digitalWrite(TEMP_POSITIVE, HIGH);
    }

    void turnOffSensor() override {
        digitalWrite(TEMP_POSITIVE, LOW);
        pinMode(DHT_PIN, OUTPUT);
        digitalWrite(DHT_PIN, LOW);
    }
};
