#include "touchscreen_binary_sensor.h"

namespace esphome {
namespace touchscreen {

void TouchscreenBinarySensor::setup() {
  this->parent_->register_listener(this);
  this->publish_initial_state(false);
}

void TouchscreenBinarySensor::touch(TouchPoint tp) {
  bool touched;
  if (this->use_raw_) {
    touched =
        (tp.x_raw >= this->x_min_ && tp.x_raw <= this->x_max_ && tp.y_raw >= this->y_min_ && tp.y_raw <= this->y_max_);
  } else {
    touched = (tp.x >= this->x_min_ && tp.x <= this->x_max_ && tp.y >= this->y_min_ && tp.y <= this->y_max_);
  }

  if (!this->pages_.empty()) {
    auto *current_page = this->parent_->get_display()->get_active_page();
    touched &= std::find(this->pages_.begin(), this->pages_.end(), current_page) != this->pages_.end();
  }
  if (touched) {
    this->publish_state(true);
  } else {
    this->release();
  }
}

void TouchscreenBinarySensor::release() { this->publish_state(false); }

}  // namespace touchscreen
}  // namespace esphome
