use esp_idf_hal::gpio::{AnyInputPin, Gpio10, Gpio6, Gpio5, InputOutput, Level, PinDriver, Pull};
use esp_idf_svc::hal::{peripheral::Peripheral, peripherals::Peripherals};
use esp_idf_sys::{esp, gpio_hold_dis, gpio_hold_en, vTaskDelay, EspError};
use esp_idf_hal::delay::Delay;
use std::time::Duration;
use esp_idf_svc::eventloop::EspSystemEventLoop;
use esp_idf_svc::ipv4::IpInfo;
use esp_idf_svc::mqtt::client::QoS::AtLeastOnce;
use esp_idf_svc::mqtt::client::QoS::ExactlyOnce;
use esp_idf_svc::mqtt::client::{EspMqttClient, LwtConfiguration, MqttClientConfiguration};
use esp_idf_svc::nvs::EspDefaultNvsPartition;
use esp_idf_svc::wifi::config::{ScanConfig, ScanType};
use esp_idf_svc::wifi::EspWifi;
use esp_idf_hal::adc::{attenuation, AdcChannelDriver, AdcDriver};

fn main() {
    // It is necessary to call this function once. Otherwise some patches to the runtime
    // implemented by esp-idf-sys might not link properly. See https://github.com/esp-rs/esp-idf-template/issues/71
    esp_idf_svc::sys::link_patches();

    // Bind the log crate to the ESP Logging facilities
    esp_idf_svc::log::EspLogger::initialize_default();

    log::info!("Hello, world!");

    let mut peripherals = Peripherals::take().unwrap();
    let mut in1 = PinDriver::input_output(peripherals.pins.gpio7).unwrap();
    let mut in2 = PinDriver::input_output(peripherals.pins.gpio6).unwrap();

    let sys_loop = EspSystemEventLoop::take().unwrap();
    let nvs = EspDefaultNvsPartition::take().unwrap();
    let mut wifi_driver = EspWifi::new(peripherals.modem, sys_loop, Some(nvs)).unwrap();
    wifi_driver.start().unwrap();
    wifi_driver.start_scan(
        &ScanConfig {
            scan_type: ScanType::Passive(Duration::from_secs(1)),
            show_hidden: false,
            ..Default::default()
        },
        true,
    ).unwrap();
    let sr = wifi_driver.get_scan_result().unwrap();
    for r in sr.iter() {
        println!("Found wifi {}", r.ssid);
    }

    let adc_config = esp_idf_hal::adc::config::Config {
        resolution: esp_idf_hal::adc::config::Resolution::Resolution12Bit,
        calibration: true,
    };
    let mut tank_driver = AdcDriver::new(peripherals.adc2, &adc_config).unwrap();
    let mut tank_channel: AdcChannelDriver<'_, { attenuation::DB_11 }, Gpio5> =
    AdcChannelDriver::new(peripherals.pins.gpio5).unwrap();

    loop {
        
        let mut delay = Delay::new_default();
        
        
        in1.set_low().unwrap();
        in2.set_high().unwrap();
        for i in 0..50 {
            delay.delay_ms(100);
            let value_up = tank_driver.read(&mut tank_channel).unwrap();
            println!("up {}", value_up);
        }
        
        let value_down = tank_driver.read(&mut tank_channel).unwrap();
        println!("down {}", value_down);
        in1.set_low().unwrap();
        in2.set_low().unwrap();
        delay.delay_ms(5000);
    }
}
