use std::{io::prelude::*, path::{Path, PathBuf}};

fn gen_bindings(out_dir: &Path)
{
	use rust_qt_binding_generator::{configuration, generate_bindings};

	let mut config = configuration::parse("bindings.json").unwrap();

	config.overwrite_implementation = true;
	config.cpp_file = out_dir.join("bindings.cc");
	config.rust.dir = out_dir.to_path_buf();

	generate_bindings(&config).unwrap();
}

fn cxx_build() -> PathBuf
{
	let mut config = cmake::Config::new(".");

	if cfg!(debug_assertions) {
		config.cxxflag("-DTYCHO_DEBUG_ASSERTIONS");
	}

	config.build()
}

fn get_link_dirs(lnk: &Path) -> Vec<PathBuf>
{
	let mut dirs = Vec::new();

	let lnk = std::fs::File::open(lnk).unwrap();
	let lnk = std::io::BufReader::new(lnk);

	for path in lnk.lines() {
		let path = PathBuf::from(path.unwrap());
		let path = path.parent().unwrap();

		let path = if cfg!(target_os = "macos") {
			path.parent().unwrap()
		} else {
			path
		};

		dirs.push(path.to_path_buf());
	}

	dirs
}

fn main()
{
	let (lty, dty, qtpre, cxx) = if cfg!(target_os = "macos") {
		("framework", "framework", "Qt", "c++")
	} else {
		("dylib", "native", "Qt5", "stdc++")
	};

	let out_dir = PathBuf::from(std::env::var("OUT_DIR").unwrap());

	gen_bindings(&out_dir);

	let cxx_dir = cxx_build();
	let lib_dir = cxx_dir.join("lib");
	let etc_dir = cxx_dir.join("etc");

	println!("cargo:rustc-link-search=native={}", lib_dir.display());
	println!("cargo:rustc-link-lib=static=maraiah-tycho-hermes");

	let dirs = get_link_dirs(&etc_dir.join("link.txt"));

	for path in dirs {
		println!("cargo:rustc-link-search={}={}", dty, path.display());
	}

	println!("cargo:rustc-link-lib={}={}Core", lty, qtpre);
	println!("cargo:rustc-link-lib={}={}Widgets", lty, qtpre);
	println!("cargo:rustc-link-lib={}={}Gui", lty, qtpre);

	println!("cargo:rustc-link-lib=dylib={}", cxx);
}

// EOF
