/*
 * main.rs
 * 
 * Copyright 2018-2024 Olivier Lecointre <olivier[at]cadexis[dot]com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not see <http://www.gnu.org/licenses/>.
 * 
 */

use core::sync::atomic::{AtomicBool, Ordering};
use glib::clone;
use gtk::glib;
use gtk::prelude::*;
use gdk_pixbuf::prelude::PixbufLoaderExt;
use gdk_pixbuf::Pixbuf;
use gdk_pixbuf::PixbufLoader;
use log::{info, debug};
use simple_logger::SimpleLogger;
use appindicator3::{prelude::*, IndicatorStatus};
use appindicator3::{Indicator, IndicatorCategory};
use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::fs;
use std::path::PathBuf;

static APP_NAME: &str = "Cadexis Rust App";
static ICON_NAME: &str = "emoticon";
static TRAY_NAME: &str = "CdxRustAppClientTray";

static MAIN_APP_OPEN: AtomicBool = AtomicBool::new(false);

pub fn set_main_app(val: bool) {
    MAIN_APP_OPEN.store(val, Ordering::Relaxed)
}

pub fn get_main_app() -> bool {
    MAIN_APP_OPEN.load(Ordering::Relaxed)
}


fn get_icon() -> Option<Pixbuf>{
	let mut ico: Option<Pixbuf> = None;
	let icon_data = include_bytes!("../emoticon.ico");
	let pixbuf_loader = PixbufLoader::new();
	if pixbuf_loader.write(icon_data).is_ok() {
		//info!("Data Loaded");
		ico = pixbuf_loader.pixbuf();
	}
	let _err = pixbuf_loader.close().is_ok();
	return ico;
}

fn on_activate_main(windows : &Rc<RefCell<HashMap<usize, glib::WeakRef<gtk::Window>>>>) {
	
	debug!("Create Main Window");
	
	set_main_app(true);

    let window = gtk::Window::new(gtk::WindowType::Toplevel);
    
    let ico = get_icon();
    
    window.connect_delete_event(|win,_| {
		debug!("Main Window {:?}", get_main_app());
		info!("Hiding Window {:?}", "App");
		//set_main_app(false);
		win.hide();
		return true.into();
	});
    window.set_title(APP_NAME);
    window.set_default_size(800, 600);
    if ico.is_some() {
		//info!("Icon Found");
		window.set_icon(ico.as_ref());
	}
	
    let button = gtk::Button::with_label("Hide Windows when clicked!");
    //button.set_default_size(80, 60);
    // … which closes the window when clicked
    button.connect_clicked(clone!(@weak window => move |_| {
		debug!("Main Window {:?}", get_main_app());
		info!("Hiding Window {:?}", "App");
		window.hide();
		//set_main_app(false);
	}));
    
    let box_ = gtk::Box::new(gtk::Orientation::Vertical, 1);
	box_.pack_start(&button,false,false,100); 
    // … with a button in it …
    window.set_child(Some(&box_));
    //window.present();
    window.show_all();
    
    windows.borrow_mut().insert(1, window.downgrade());
}

fn show_main_window(windows : &Rc<RefCell<HashMap<usize, glib::WeakRef<gtk::Window>>>>) {
	debug!("Main app {:?}", get_main_app()); 
	if get_main_app() {
		for window in windows.borrow().values() {
            if let Some(w) = window.upgrade() {
				debug!("Show window"); 
                w.show();
                w.hide();
                w.show();
                set_main_app(true);
            }
        }
		return;
	}	
	on_activate_main(&windows);
}

pub fn get_string(_value: &Option<String>) -> String {
	match _value {
	  Some(key) => key.clone(),
	  None => String::from("")
	}
}

pub fn resolve_path(_path : Option<String>) -> Option<String> {
		if _path.is_none() {
			return None;
		}
		let ppath = get_string(&_path);
		let absolute = fs::canonicalize(PathBuf::from(ppath.clone())).ok();
		if absolute.is_none() {
			return _path;
		}
		let spath = absolute.clone().unwrap();
		if !spath.exists() {
			return Some(spath.to_str().unwrap().to_string());
		}
		return Some(spath.to_str().unwrap().to_string());
}

fn main() {
	SimpleLogger::new().init().unwrap();
	info!("Starting app {:?}", APP_NAME);
    let _ = gtk::init();
    
    let windows: Rc<RefCell<HashMap<usize, glib::WeakRef<gtk::Window>>>> = Rc::new(RefCell::new(HashMap::new()));
	
	show_main_window(&windows);
    
    let icon_path = resolve_path(Some(String::from("."))).unwrap();
	info!("Icon path {:?}", icon_path);
    
	let indicator = Indicator::with_path(TRAY_NAME, ICON_NAME, IndicatorCategory::ApplicationStatus,icon_path.as_str());
   
    indicator.set_status(IndicatorStatus::Active);
    indicator.set_title(Some(APP_NAME));
    let menu = gtk::Menu::new();
    let item1 = gtk::MenuItem::with_label("Main");
    item1.connect_activate(glib::clone!(@weak windows => move |_| {
        show_main_window(&windows);
    }));

    menu.append(&item1);
    item1.show();
    
    let item2= gtk::MenuItem::with_label("Exit");
    item2.connect_activate(
		|_| {
      		info!("Exiting App {:?}", APP_NAME);
			gtk::main_quit();
        }
	);
	menu.append(&item2);
    item2.show();
    
    indicator.set_secondary_activate_target(Some(&item1));
    indicator.set_menu(Some(&menu));
    
	gtk::main();
}