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

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

   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;

   generate_bindings(&config).unwrap();

   let mut config = cmake::Config::new(".");

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

   let out_dir = config.build();
   let lib_dir = out_dir.join("lib");
   let etc_dir = out_dir.join("etc");

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

   let fp = std::fs::File::open(etc_dir.join("link.txt")).unwrap();
   let fp = std::io::BufReader::new(fp);

   for ln in fp.lines() {
      let ln = ln.unwrap();

      let path = PathBuf::from(&ln);
      let path = path.parent().unwrap();

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

      println!("cargo:rustc-link-search={}={}", ty, path.display());
   }

   let (ty, pre) = if cfg!(target_os = "macos") {
      ("framework", "Qt")
   } else {
      ("dylib", "Qt5")
   };

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

   if !cfg!(target_os = "macos") {
      println!("cargo:rustc-link-lib=dylib=stdc++");
   }
}

// EOF
