#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use std::fs;
use std::env;
use std::sync::mpsc::{Sender, Receiver};

use json::{JsonValue, object};

#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use br_db::Db;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use br_db::config::Config as DbConfig;
#[cfg(any(feature = "cache"))]
use br_cache::Cache;
#[cfg(any(feature = "kafka"))]
use br_kafka::Kafka;

use lazy_static::lazy_static;
use std::sync::{Arc, mpsc, Mutex};
use std::collections::HashMap;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use std::path::PathBuf;
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use std::process::exit;

#[cfg(any(feature = "cache"))]
use br_cache::CacheConfig;

#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use log::{error};
#[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
use log::info;
use crate::config::Config;

pub mod addon;
pub mod model;
pub mod action;
pub mod config;

/// 集合工具
#[derive(Clone)]
pub struct Tools {
    #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
    pub db: Db,
    #[cfg(any(feature = "cache"))]
    pub cache: Cache,
    #[cfg(any(feature = "kafka"))]
    pub kafka: Kafka,

    pub config: Config,
}

impl Tools {
    pub fn new() -> Self {
        Self {
            #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
            db: Db::None,
            #[cfg(any(feature = "cache"))]
            cache: Cache::connect(object! {}),
            #[cfg(any(feature = "kafka"))]
            kafka: Kafka::connect(object! {}),
            config: Config::default(),
        }
    }
    #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
    pub fn set_db(&mut self, config_filename: &str) -> &mut Self {
        let conf = fs::read_to_string(config_filename.clone());
        match conf {
            Ok(str) => {
                match json::parse(str.as_str().clone()) {
                    Ok(config) => {
                        self.db = Db::new(config);
                        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
                    }
                    Err(e) => {
                        error!("数据库配置文件错误: {}",e.to_string());
                    }
                }
            }
            Err(_) => {
                let data = DbConfig::default().to_json();
                let path_buf = PathBuf::from(config_filename.clone());
                fs::create_dir_all(config_filename.trim_end_matches(path_buf.file_name().unwrap().to_str().unwrap())).unwrap();
                fs::write(config_filename, data.to_string()).expect("创建数据库配置文件失败");
                info!("创建配置文件成功请重启");
                exit(0)
            }
        }
        self
    }
    #[cfg(any(feature = "mysql", feature = "mssql", feature = "sqlite"))]
    pub fn set_db_json(&mut self, config: JsonValue) -> &mut Self {
        self.db = Db::new(config);
        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
        self
    }
    #[cfg(any(feature = "cache"))]
    pub fn set_cache(&mut self, config_path: &str) -> &mut Self {
        let conf = fs::read_to_string(config_path.clone());
        match conf {
            Ok(str) => {
                match json::parse(str.as_str().clone()) {
                    Ok(config) => {
                        self.cache = Cache::connect(config);
                        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
                    }
                    Err(e) => {
                        error!("缓存配置文件错误: {}",e.to_string());
                    }
                }
            }
            Err(_) => {
                let data = CacheConfig::default().to_json();
                fs::write(config_path, data.to_string()).expect("创建缓存配置文件失败");
                exit(101)
            }
        }
        self
    }
    #[cfg(any(feature = "kafka"))]
    pub fn set_kafka(&mut self, config_path: &str) -> &mut Self {
        let conf = fs::read_to_string(config_path.clone()).unwrap();
        match json::parse(conf.as_str().clone()) {
            Ok(config) => {
                self.kafka = Kafka::connect(config);
                PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
            }
            Err(e) => {
                error!("kafka配置文件错误: {}", e.to_string());
            }
        }
        self
    }
    /// 全局配置
    pub fn set_config(&mut self, path: &str) -> &mut Self {
        self.config = Config::load(path);
        PLUGIN_TOOLS.lock().unwrap().insert("tools".to_string(), self.clone());
        self
    }
    /// 设置WSS内存通道
    pub fn set_wss_channel(&mut self) -> &mut Self {
        let (tx, rx) = mpsc::channel();
        PLUGIN_WS_TX.lock().unwrap().insert("wss".to_string(), tx.clone());

        let receiver = Arc::new(Mutex::new(rx));
        PLUGIN_WS_RX.lock().unwrap().insert("wss".to_string(), Arc::clone(&receiver));
        self
    }
}

lazy_static! {
    /// 工具集合
    pub static ref PLUGIN_TOOLS: Mutex<HashMap<String,Tools>> =Mutex::new(HashMap::new());
    pub static ref PLUGIN_WS_TX: Mutex<HashMap<String,Sender<JsonValue>>> =Mutex::new(HashMap::new());
    pub static ref PLUGIN_WS_RX: Mutex<HashMap<String,Arc<Mutex<Receiver<JsonValue>>>>> =Mutex::new(HashMap::new());
}


/// 按钮颜色
pub enum BtnColor {
    Red,
    Blue,
    Yellow,
    Green,
}

impl BtnColor {
    fn from(self) -> &'static str {
        match self {
            BtnColor::Red => "red",
            BtnColor::Blue => "blue",
            BtnColor::Yellow => "yellow",
            BtnColor::Green => "green",
        }
    }
}

/// 按钮模式
pub enum BtnMode {
    Form,
    Url,
    Api,
    Download,
    Path,
}

impl BtnMode {
    fn from(self) -> &'static str {
        match self {
            BtnMode::Form => "form",
            BtnMode::Api => "api",
            BtnMode::Download => "download",
            BtnMode::Url => "url",
            BtnMode::Path => "path",
        }
    }
}

/// 通知消息模式
pub enum NotifyMode {
    Primary,
    Info,
    Negative,
    Warning,
    Positive,
}

impl NotifyMode {
    fn from(self) -> &'static str {
        match self {
            NotifyMode::Primary => "primary",
            NotifyMode::Info => "info",
            NotifyMode::Negative => "negative",
            NotifyMode::Warning => "warning",
            NotifyMode::Positive => "positive",
        }
    }
}

/// 返回响应
#[derive(Clone, Debug)]
pub struct Response(i32, &'static str, JsonValue);

impl Response {
    /// 获取状态
    pub fn get_code(self) -> i32 {
        self.0
    }
    /// 获取消息
    pub fn get_msg(self) -> &'static str {
        self.1
    }
    /// 获取数据
    pub fn get_data(self) -> JsonValue {
        self.2
    }
    /// 获取业务数据
    pub fn get_data_data(self) -> JsonValue {
        self.get_data()["data"].clone()
    }
    /// 获取业务反馈编号
    pub fn get_data_code(self) -> i32 {
        self.get_data()["code"].as_i32().unwrap()
    }
    /// 获取业务提示消息
    pub fn get_data_msg(self) -> String {
        self.get_data()["msg"].to_string()
    }
    pub fn into(self) -> (i32, &'static str, JsonValue) {
        return (self.0, self.1, self.2);
    }
    /// 成功
    pub fn success(data: JsonValue, msg: &str) -> Self {
        let data = object! {code: 0,data:data,msg: msg.to_string()};
        Self(200, "json", data)
    }
    /// 失败
    pub fn fail(msg: &str) -> Self {
        let data = object! {
            code: -1,
            msg: msg.to_string()
        };
        Self(200, "json", data)
    }
    /// 通知消息
    pub fn notify(msg: &str, caption: &str, mode: NotifyMode, timeout: usize, path: &str) -> Self {
        let data = object! {
            code: -1,
            msg: msg.to_string(),
            caption:caption.clone(),
            mode:mode.from(),
            timeout:timeout.clone(),
            path:path.clone()
        };
        Self(200, "json", data)
    }

    /// 登陆
    pub fn login(msg: &str) -> Self {
        let data = object! {code: 1000,msg: msg.to_string(),};
        Self(200, "json", data)
    }
    /// 下载
    pub fn download(filename: &str) -> Self {
        Self(200, "download", filename.into())
    }
    /// 重定向
    pub fn redirect(url: &str) -> Self {
        Self(301, "url", url.into())
    }
}

pub struct ApiModel {}

impl ApiModel {
    pub fn run(args_new: Vec<String>) -> (bool, String, String, String, String, JsonValue) {
        let mut args: Vec<String> = env::args().collect();
        if args_new.len() > 0 {
            args = args_new.clone();
        }
        if args.len() <= 1 {
            return (false, "参数错误".to_string(), "".to_string(), "".to_string(), "".to_string(), object! {});
        }
        let mode = args[1].as_str();
        let api = args[2].as_str();
        if api.is_empty() {
            return (false, "无API参数".to_string(), "".to_string(), "".to_string(), "".to_string(), object! {});
        }
        let api: Vec<&str> = api.split(".").collect();
        if api.len() != 3 {
            return (false, "API参数错误".to_string(), "".to_string(), "".to_string(), "".to_string(), object! {});
        }
        let data = args[3].as_str();
        if data.is_empty() {
            return (false, "请求参数无效".to_string(), "".to_string(), "".to_string(), "".to_string(), object! {});
        }
        let data = json::parse(data).unwrap();
        return (true, mode.to_string(), api[0].to_string(), api[1].to_string(), api[2].to_string(), data);
    }
    pub fn fail(msg: &str) -> JsonValue {
        let data = object! {code:-1,msg:msg};
        return data;
    }
}


