// Generated by gir (https://github.com/gtk-rs/gir @ 350409c)
// from .. (@ ed21eb4+)
// from ../gir-files (@ 38b7451)
// DO NOT EDIT

use gweather_sys::*;
use std::mem::{align_of, size_of};
use std::env;
use std::error::Error;
use std::ffi::OsString;
use std::path::Path;
use std::process::Command;
use std::str;
use tempfile::Builder;

static PACKAGES: &[&str] = &["gweather-3.0"];

#[derive(Clone, Debug)]
struct Compiler {
    pub args: Vec<String>,
}

impl Compiler {
    pub fn new() -> Result<Self, Box<dyn Error>> {
        let mut args = get_var("CC", "cc")?;
        args.push("-Wno-deprecated-declarations".to_owned());
        // For _Generic
        args.push("-std=c11".to_owned());
        // For %z support in printf when using MinGW.
        args.push("-D__USE_MINGW_ANSI_STDIO".to_owned());
        args.extend(get_var("CFLAGS", "")?);
        args.extend(get_var("CPPFLAGS", "")?);
        args.extend(pkg_config_cflags(PACKAGES)?);
        Ok(Self { args })
    }

    pub fn compile(&self, src: &Path, out: &Path) -> Result<(), Box<dyn Error>> {
        let mut cmd = self.to_command();
        cmd.arg(src);
        cmd.arg("-o");
        cmd.arg(out);
        let status = cmd.spawn()?.wait()?;
        if !status.success() {
            return Err(format!("compilation command {:?} failed, {}", &cmd, status).into());
        }
        Ok(())
    }

    fn to_command(&self) -> Command {
        let mut cmd = Command::new(&self.args[0]);
        cmd.args(&self.args[1..]);
        cmd
    }
}

fn get_var(name: &str, default: &str) -> Result<Vec<String>, Box<dyn Error>> {
    match env::var(name) {
        Ok(value) => Ok(shell_words::split(&value)?),
        Err(env::VarError::NotPresent) => Ok(shell_words::split(default)?),
        Err(err) => Err(format!("{} {}", name, err).into()),
    }
}

fn pkg_config_cflags(packages: &[&str]) -> Result<Vec<String>, Box<dyn Error>> {
    if packages.is_empty() {
        return Ok(Vec::new());
    }
    let pkg_config = env::var_os("PKG_CONFIG")
        .unwrap_or_else(|| OsString::from("pkg-config"));
    let mut cmd = Command::new(pkg_config);
    cmd.arg("--cflags");
    cmd.args(packages);
    let out = cmd.output()?;
    if !out.status.success() {
        return Err(format!("command {:?} returned {}",
                           &cmd, out.status).into());
    }
    let stdout = str::from_utf8(&out.stdout)?;
    Ok(shell_words::split(stdout.trim())?)
}


#[derive(Copy, Clone, Debug, Eq, PartialEq)]
struct Layout {
    size: usize,
    alignment: usize,
}

#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
struct Results {
    /// Number of successfully completed tests.
    passed: usize,
    /// Total number of failed tests (including those that failed to compile).
    failed: usize,
}

impl Results {
    fn record_passed(&mut self) {
        self.passed += 1;
    }
    fn record_failed(&mut self) {
        self.failed += 1;
    }
    fn summary(&self) -> String {
        format!("{} passed; {} failed", self.passed, self.failed)
    }
    fn expect_total_success(&self) {
        if self.failed == 0 {
            println!("OK: {}", self.summary());
        } else {
            panic!("FAILED: {}", self.summary());
        };
    }
}

#[test]
fn cross_validate_constants_with_c() {
    let mut c_constants: Vec<(String, String)> = Vec::new();

    for l in get_c_output("constant").unwrap().lines() {
        let mut words = l.trim().split(';');
        let name = words.next().expect("Failed to parse name").to_owned();
        let value = words
            .next()
            .and_then(|s| s.parse().ok())
            .expect("Failed to parse value");
        c_constants.push((name, value));
    }

    let mut results = Results::default();

    for ((rust_name, rust_value), (c_name, c_value)) in
        RUST_CONSTANTS.iter().zip(c_constants.iter())
    {
        if rust_name != c_name {
            results.record_failed();
            eprintln!("Name mismatch:\nRust: {:?}\nC:    {:?}", rust_name, c_name,);
            continue;
        }

        if rust_value != c_value {
            results.record_failed();
            eprintln!(
                "Constant value mismatch for {}\nRust: {:?}\nC:    {:?}",
                rust_name, rust_value, &c_value
            );
            continue;
        }

        results.record_passed();
    }

    results.expect_total_success();
}

#[test]
fn cross_validate_layout_with_c() {
    let mut c_layouts = Vec::new();

    for l in get_c_output("layout").unwrap().lines() {
        let mut words = l.trim().split(';');
        let name = words.next().expect("Failed to parse name").to_owned();
        let size = words
            .next()
            .and_then(|s| s.parse().ok())
            .expect("Failed to parse size");
        let alignment = words
            .next()
            .and_then(|s| s.parse().ok())
            .expect("Failed to parse alignment");
        c_layouts.push((name, Layout { size, alignment }));
    }

    let mut results = Results::default();

    for ((rust_name, rust_layout), (c_name, c_layout)) in
        RUST_LAYOUTS.iter().zip(c_layouts.iter())
    {
        if rust_name != c_name {
            results.record_failed();
            eprintln!("Name mismatch:\nRust: {:?}\nC:    {:?}", rust_name, c_name,);
            continue;
        }

        if rust_layout != c_layout {
            results.record_failed();
            eprintln!(
                "Layout mismatch for {}\nRust: {:?}\nC:    {:?}",
                rust_name, rust_layout, &c_layout
            );
            continue;
        }

        results.record_passed();
    }

    results.expect_total_success();
}

fn get_c_output(name: &str) -> Result<String, Box<dyn Error>> {
    let tmpdir = Builder::new().prefix("abi").tempdir()?;
    let exe = tmpdir.path().join(name);
    let c_file = Path::new("tests").join(name).with_extension("c");

    let cc = Compiler::new().expect("configured compiler");
    cc.compile(&c_file, &exe)?;

    let mut abi_cmd = Command::new(exe);
    let output = abi_cmd.output()?;
    if !output.status.success() {
        return Err(format!("command {:?} failed, {:?}", &abi_cmd, &output).into());
    }

    Ok(String::from_utf8(output.stdout)?)
}

const RUST_LAYOUTS: &[(&str, Layout)] = &[
    ("GWeatherConditionPhenomenon", Layout {size: size_of::<GWeatherConditionPhenomenon>(), alignment: align_of::<GWeatherConditionPhenomenon>()}),
    ("GWeatherConditionQualifier", Layout {size: size_of::<GWeatherConditionQualifier>(), alignment: align_of::<GWeatherConditionQualifier>()}),
    ("GWeatherConditions", Layout {size: size_of::<GWeatherConditions>(), alignment: align_of::<GWeatherConditions>()}),
    ("GWeatherDistanceUnit", Layout {size: size_of::<GWeatherDistanceUnit>(), alignment: align_of::<GWeatherDistanceUnit>()}),
    ("GWeatherFormatOptions", Layout {size: size_of::<GWeatherFormatOptions>(), alignment: align_of::<GWeatherFormatOptions>()}),
    ("GWeatherInfoClass", Layout {size: size_of::<GWeatherInfoClass>(), alignment: align_of::<GWeatherInfoClass>()}),
    ("GWeatherLocationEntry", Layout {size: size_of::<GWeatherLocationEntry>(), alignment: align_of::<GWeatherLocationEntry>()}),
    ("GWeatherLocationEntryClass", Layout {size: size_of::<GWeatherLocationEntryClass>(), alignment: align_of::<GWeatherLocationEntryClass>()}),
    ("GWeatherLocationLevel", Layout {size: size_of::<GWeatherLocationLevel>(), alignment: align_of::<GWeatherLocationLevel>()}),
    ("GWeatherMoonLatitude", Layout {size: size_of::<GWeatherMoonLatitude>(), alignment: align_of::<GWeatherMoonLatitude>()}),
    ("GWeatherMoonPhase", Layout {size: size_of::<GWeatherMoonPhase>(), alignment: align_of::<GWeatherMoonPhase>()}),
    ("GWeatherPressureUnit", Layout {size: size_of::<GWeatherPressureUnit>(), alignment: align_of::<GWeatherPressureUnit>()}),
    ("GWeatherProvider", Layout {size: size_of::<GWeatherProvider>(), alignment: align_of::<GWeatherProvider>()}),
    ("GWeatherSky", Layout {size: size_of::<GWeatherSky>(), alignment: align_of::<GWeatherSky>()}),
    ("GWeatherSpeedUnit", Layout {size: size_of::<GWeatherSpeedUnit>(), alignment: align_of::<GWeatherSpeedUnit>()}),
    ("GWeatherTemperatureUnit", Layout {size: size_of::<GWeatherTemperatureUnit>(), alignment: align_of::<GWeatherTemperatureUnit>()}),
    ("GWeatherTimezoneMenu", Layout {size: size_of::<GWeatherTimezoneMenu>(), alignment: align_of::<GWeatherTimezoneMenu>()}),
    ("GWeatherTimezoneMenuClass", Layout {size: size_of::<GWeatherTimezoneMenuClass>(), alignment: align_of::<GWeatherTimezoneMenuClass>()}),
    ("GWeatherWindDirection", Layout {size: size_of::<GWeatherWindDirection>(), alignment: align_of::<GWeatherWindDirection>()}),
];

const RUST_CONSTANTS: &[(&str, &str)] = &[
    ("(gint) GWEATHER_DISTANCE_UNIT_DEFAULT", "1"),
    ("(gint) GWEATHER_DISTANCE_UNIT_INVALID", "0"),
    ("(gint) GWEATHER_DISTANCE_UNIT_KM", "3"),
    ("(gint) GWEATHER_DISTANCE_UNIT_METERS", "2"),
    ("(gint) GWEATHER_DISTANCE_UNIT_MILES", "4"),
    ("(guint) GWEATHER_FORMAT_OPTION_DEFAULT", "0"),
    ("(guint) GWEATHER_FORMAT_OPTION_NO_CAPITALIZATION", "2"),
    ("(guint) GWEATHER_FORMAT_OPTION_SENTENCE_CAPITALIZATION", "1"),
    ("(gint) GWEATHER_LOCATION_ADM1", "3"),
    ("(gint) GWEATHER_LOCATION_CITY", "4"),
    ("(gint) GWEATHER_LOCATION_COUNTRY", "2"),
    ("(gint) GWEATHER_LOCATION_DETACHED", "6"),
    ("GWEATHER_LOCATION_ENTRY_H", "1"),
    ("(gint) GWEATHER_LOCATION_NAMED_TIMEZONE", "7"),
    ("(gint) GWEATHER_LOCATION_REGION", "1"),
    ("(gint) GWEATHER_LOCATION_WEATHER_STATION", "5"),
    ("(gint) GWEATHER_LOCATION_WORLD", "0"),
    ("(gint) GWEATHER_PHENOMENON_DRIZZLE", "1"),
    ("(gint) GWEATHER_PHENOMENON_DUST", "17"),
    ("(gint) GWEATHER_PHENOMENON_DUSTSTORM", "20"),
    ("(gint) GWEATHER_PHENOMENON_DUST_WHIRLS", "23"),
    ("(gint) GWEATHER_PHENOMENON_FOG", "11"),
    ("(gint) GWEATHER_PHENOMENON_FUNNEL_CLOUD", "21"),
    ("(gint) GWEATHER_PHENOMENON_HAIL", "7"),
    ("(gint) GWEATHER_PHENOMENON_HAZE", "15"),
    ("(gint) GWEATHER_PHENOMENON_ICE_CRYSTALS", "5"),
    ("(gint) GWEATHER_PHENOMENON_ICE_PELLETS", "6"),
    ("(gint) GWEATHER_PHENOMENON_INVALID", "-1"),
    ("(gint) GWEATHER_PHENOMENON_LAST", "24"),
    ("(gint) GWEATHER_PHENOMENON_MIST", "10"),
    ("(gint) GWEATHER_PHENOMENON_NONE", "0"),
    ("(gint) GWEATHER_PHENOMENON_RAIN", "2"),
    ("(gint) GWEATHER_PHENOMENON_SAND", "14"),
    ("(gint) GWEATHER_PHENOMENON_SANDSTORM", "19"),
    ("(gint) GWEATHER_PHENOMENON_SMALL_HAIL", "8"),
    ("(gint) GWEATHER_PHENOMENON_SMOKE", "12"),
    ("(gint) GWEATHER_PHENOMENON_SNOW", "3"),
    ("(gint) GWEATHER_PHENOMENON_SNOW_GRAINS", "4"),
    ("(gint) GWEATHER_PHENOMENON_SPRAY", "16"),
    ("(gint) GWEATHER_PHENOMENON_SQUALL", "18"),
    ("(gint) GWEATHER_PHENOMENON_TORNADO", "22"),
    ("(gint) GWEATHER_PHENOMENON_UNKNOWN_PRECIPITATION", "9"),
    ("(gint) GWEATHER_PHENOMENON_VOLCANIC_ASH", "13"),
    ("(gint) GWEATHER_PRESSURE_UNIT_ATM", "7"),
    ("(gint) GWEATHER_PRESSURE_UNIT_DEFAULT", "1"),
    ("(gint) GWEATHER_PRESSURE_UNIT_HPA", "3"),
    ("(gint) GWEATHER_PRESSURE_UNIT_INCH_HG", "6"),
    ("(gint) GWEATHER_PRESSURE_UNIT_INVALID", "0"),
    ("(gint) GWEATHER_PRESSURE_UNIT_KPA", "2"),
    ("(gint) GWEATHER_PRESSURE_UNIT_MB", "4"),
    ("(gint) GWEATHER_PRESSURE_UNIT_MM_HG", "5"),
    ("(guint) GWEATHER_PROVIDER_ALL", "61"),
    ("(guint) GWEATHER_PROVIDER_IWIN", "4"),
    ("(guint) GWEATHER_PROVIDER_METAR", "1"),
    ("(guint) GWEATHER_PROVIDER_MET_NO", "16"),
    ("(guint) GWEATHER_PROVIDER_NONE", "0"),
    ("(guint) GWEATHER_PROVIDER_OWM", "32"),
    ("(guint) GWEATHER_PROVIDER_YAHOO", "8"),
    ("(gint) GWEATHER_QUALIFIER_BLOWING", "9"),
    ("(gint) GWEATHER_QUALIFIER_DRIFTING", "11"),
    ("(gint) GWEATHER_QUALIFIER_FREEZING", "12"),
    ("(gint) GWEATHER_QUALIFIER_HEAVY", "4"),
    ("(gint) GWEATHER_QUALIFIER_INVALID", "-1"),
    ("(gint) GWEATHER_QUALIFIER_LAST", "13"),
    ("(gint) GWEATHER_QUALIFIER_LIGHT", "2"),
    ("(gint) GWEATHER_QUALIFIER_MODERATE", "3"),
    ("(gint) GWEATHER_QUALIFIER_NONE", "0"),
    ("(gint) GWEATHER_QUALIFIER_PARTIAL", "7"),
    ("(gint) GWEATHER_QUALIFIER_PATCHES", "6"),
    ("(gint) GWEATHER_QUALIFIER_SHALLOW", "5"),
    ("(gint) GWEATHER_QUALIFIER_SHOWERS", "10"),
    ("(gint) GWEATHER_QUALIFIER_THUNDERSTORM", "8"),
    ("(gint) GWEATHER_QUALIFIER_VICINITY", "1"),
    ("(gint) GWEATHER_SKY_BROKEN", "1"),
    ("(gint) GWEATHER_SKY_CLEAR", "0"),
    ("(gint) GWEATHER_SKY_FEW", "3"),
    ("(gint) GWEATHER_SKY_INVALID", "-1"),
    ("(gint) GWEATHER_SKY_LAST", "5"),
    ("(gint) GWEATHER_SKY_OVERCAST", "4"),
    ("(gint) GWEATHER_SKY_SCATTERED", "2"),
    ("(gint) GWEATHER_SPEED_UNIT_BFT", "6"),
    ("(gint) GWEATHER_SPEED_UNIT_DEFAULT", "1"),
    ("(gint) GWEATHER_SPEED_UNIT_INVALID", "0"),
    ("(gint) GWEATHER_SPEED_UNIT_KNOTS", "5"),
    ("(gint) GWEATHER_SPEED_UNIT_KPH", "3"),
    ("(gint) GWEATHER_SPEED_UNIT_MPH", "4"),
    ("(gint) GWEATHER_SPEED_UNIT_MS", "2"),
    ("(gint) GWEATHER_TEMP_UNIT_CENTIGRADE", "3"),
    ("(gint) GWEATHER_TEMP_UNIT_DEFAULT", "1"),
    ("(gint) GWEATHER_TEMP_UNIT_FAHRENHEIT", "4"),
    ("(gint) GWEATHER_TEMP_UNIT_INVALID", "0"),
    ("(gint) GWEATHER_TEMP_UNIT_KELVIN", "2"),
    ("GWEATHER_TIMEZONE_MENU_H", "1"),
    ("(gint) GWEATHER_WIND_E", "5"),
    ("(gint) GWEATHER_WIND_ENE", "4"),
    ("(gint) GWEATHER_WIND_ESE", "6"),
    ("(gint) GWEATHER_WIND_INVALID", "-1"),
    ("(gint) GWEATHER_WIND_LAST", "17"),
    ("(gint) GWEATHER_WIND_N", "1"),
    ("(gint) GWEATHER_WIND_NE", "3"),
    ("(gint) GWEATHER_WIND_NNE", "2"),
    ("(gint) GWEATHER_WIND_NNW", "16"),
    ("(gint) GWEATHER_WIND_NW", "15"),
    ("(gint) GWEATHER_WIND_S", "9"),
    ("(gint) GWEATHER_WIND_SE", "7"),
    ("(gint) GWEATHER_WIND_SSE", "8"),
    ("(gint) GWEATHER_WIND_SSW", "10"),
    ("(gint) GWEATHER_WIND_SW", "11"),
    ("(gint) GWEATHER_WIND_VARIABLE", "0"),
    ("(gint) GWEATHER_WIND_W", "13"),
    ("(gint) GWEATHER_WIND_WNW", "14"),
    ("(gint) GWEATHER_WIND_WSW", "12"),
];


