use std::collections::HashMap;
use std::env;
use std::sync::Arc;

use tokio::sync::mpsc::UnboundedReceiver;
use tokio::sync::{Mutex, RwLock};
use tokio::time::{sleep, Duration};

use twitch_irc::login::StaticLoginCredentials;
use twitch_irc::message::{PrivmsgMessage, ServerMessage};
use twitch_irc::transport::tcp::{TCPTransport, TLS};
use twitch_irc::{ClientConfig, SecureTCPTransport, TwitchIRCClient};

use dotenv::dotenv;

use casual_logger::Log;

use crate::core::ratelimiter::RateLimiter;

use crate::core::bot_actions::actions_util::BotAR;
use crate::core::botmodules::ModulesManager;
use crate::core::identity::{IdentityManager, Permissible,self};

use crate::core::botlog;
use crate::core::chat::Chat;


#[derive(Debug, PartialEq, Eq, Clone)]
pub enum ChangeResult {
    Success(String),
    Failed(String),
    NoChange(String),
}



#[derive(Debug, PartialEq, Eq, Hash, Clone)]

// pub enum ChType {
//     Channel(String),
// }
//
// pub use ChType::Channel;
//
//simplifying from enum to struct
pub struct Channel(pub String);

use super::botmodules::StatusType;

#[derive(Clone)]
pub struct BotManagers {
    pub identity: Arc<RwLock<IdentityManager>>,
    pub chat: Chat,
}

impl BotManagers {
    pub fn init(
        ratelimiters: HashMap<Channel, RateLimiter>,
        client: TwitchIRCClient<TCPTransport<TLS>, StaticLoginCredentials>,
    ) -> BotManagers {
        BotManagers {
            identity: Arc::new(RwLock::new(IdentityManager::init())),
            chat: Chat::init(ratelimiters, client),
        }
    }

    pub fn r_identity(self) -> Arc<RwLock<IdentityManager>> {
        self.identity
    }
}

pub struct ArcBox<T: Clone>(pub Arc<Mutex<T>>);

impl<T: Clone> ArcBox<T> {
    pub fn inst(&self) -> &Mutex<T> {
        &self.0
    }
}

pub struct BotInstance {
    pub prefix: char,
    pub bot_channel: Channel,
    pub incoming_messages: Arc<RwLock<UnboundedReceiver<ServerMessage>>>,
    pub botmodules: Arc<ModulesManager>,
    pub twitch_oauth: String,
    pub bot_channels: Vec<Channel>,
    pub botmgrs: BotManagers,
    //modesmgr : ModesManager, // [FUTURE] Silent/Quiet , uwu , frisky/horny
}

impl BotInstance {
    pub async fn init() -> BotInstance {
        dotenv().ok();

        let login_name = env::var("login_name").unwrap().to_owned();
        let oauth_token = env::var("access_token").unwrap().to_owned();
        let prefix = env::var("prefix")
            .unwrap()
            .to_owned()
            .chars()
            .next()
            .expect("ERROR : when defining prefix");

        let mut botchannels = Vec::new();

        for chnl in env::var("bot_channels").unwrap().split(',') {
            botchannels.push(Channel(String::from(chnl)));
        }

        let config = ClientConfig::new_simple(StaticLoginCredentials::new(
            login_name.to_owned(),
            Some(oauth_token.to_owned()),
        ));

        let (incoming_messages, client) =
            TwitchIRCClient::<SecureTCPTransport, StaticLoginCredentials>::new(config);

        let mut ratelimiters = HashMap::new();

        for Channel(chnl) in &botchannels {
            // For each channel in botchannels , join & create ratelimiters

            client.join(chnl.to_owned()).unwrap();

            let n = RateLimiter::new();
            ratelimiters.insert(Channel(String::from(chnl)), n);
        }


        tokio::spawn(async { 
            loop {
                let routine_mins = 60 * 60 * 24 ; // Every 1 Day
                // let routine_mins = 1; // Every 1 Minute
                Log::remove_old_logs();
                Log::info(&format!("Internal Purge Routine Triggered - running every {} mins",routine_mins));
                Log::flush();
                sleep(Duration::from_secs(60 * routine_mins)).await
                }
        });


        BotInstance {
            prefix,
            bot_channel: Channel(login_name),
            incoming_messages: Arc::new(RwLock::new(incoming_messages)),
            botmodules: ModulesManager::init().await,
            twitch_oauth: oauth_token,
            bot_channels: botchannels,
            botmgrs: BotManagers::init(ratelimiters, client),
        }
    }

    pub async fn runner(self) {
        // Main Game Loop

        let bot = Arc::new(RwLock::new(self));

        let join_handle = tokio::spawn(async move {
            let botlock = bot.read().await;
            let mut msglock = botlock.incoming_messages.write().await;

            while let Some(message) = msglock.recv().await {

                match message {
                    ServerMessage::Notice(msg) => {
                        botlog::notice(
                            format!("NOTICE : (#{:?}) {}", msg.channel_login, msg.message_text)
                                .as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                    }
                    ServerMessage::Privmsg(msg) => {
                        botlog::debug(
                            format!(
                                "[Twitch Chat > {}] > {}: {}",
                                msg.channel_login, msg.sender.name, msg.message_text
                            )
                            .as_str(),
                            Some("BotInstance > runner()".to_string()),
                            Some(&msg),
                        );

                        BotInstance::listener_main_prvmsg(Arc::clone(&bot), &msg).await;
                    }
                    ServerMessage::Whisper(msg) => {
                        botlog::debug(
                            format!("[Whisper] {}: {}", msg.sender.name, msg.message_text).as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                    }
                    ServerMessage::Join(msg) => {
                        botlog::notice(
                            format!("JOINED: {}", msg.channel_login).as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                    }
                    ServerMessage::Part(msg) => {
                        botlog::notice(
                            format!("PARTED: {}", msg.channel_login).as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                    }
                    _ => {}
                };
                Log::flush();
            }
        });

        join_handle.await.unwrap();
    }

    pub fn get_identity(&self) -> Arc<RwLock<IdentityManager>> {
        Arc::clone(&self.botmgrs.identity)
    }

    pub fn get_prefix(&self) -> char {
        self.prefix
    }

    // -----------------
    // PRIVATE FUNCTIONS

    async fn listener_main_prvmsg(bot: BotAR, msg: &PrivmsgMessage) {
        botlog::trace(
            ">> Inner listenermain_prvmsg()",
            Some("BotInstance > listener_main_prvmsg()".to_string()),
            Some(msg),
        );

        // // [ ] #todo Need to run through all Listener Bodies for Enabled Modules for the context of the message (e.g., ModStatus is Enabled in the context for the channel)

        let botlock = bot.read().await;
        let actsdb = Arc::clone(&botlock.botmodules.botactions);
        let actsdblock = actsdb.read().await;

        botlog::debug(
            format!("# of BotModules: {}", (*actsdblock).len()).as_str(),
            Some("BotInstance > listener_main_prvmsg()".to_string()),
            Some(msg),
        );

        for acts in (*actsdblock).values() {
            for a in acts {
                match a {
                    crate::core::botmodules::BotAction::C(c) => {
                        /*
                        BotCommand handling -
                        - [x] Checks if the input message is a prefix with command name or alias
                        - [x] Validate User can run based on identityModule(From_Bot)::can_user_run(
                                                        _usr:String,
                                                        _channelname:ChType,
                                                        _chat_badge:ChatBadge,
                                                        _cmdreqroles:Vec<UserRole>)
                        */

                        botlog::trace(
                            "Reviewing internal commands",
                            Some("BotInstance > listener_main_prvmsg()".to_string()),
                            Some(msg),
                        );

                        let inpt = msg
                            .message_text
                            .split(' ')
                            .next()
                            .expect("ERROR during BotCommand");

                        // [x] Check if a bot command based on ...
                        //    [x] prefix + command

                        let mut confirmed_bot_command = false;

                        let instr = bot.read().await.get_prefix();
                        if inpt == String::from(instr) + c.command.as_str() {
                            confirmed_bot_command = true;
                        }

                        //    [x] prefix + alias
                        for alias in &c.alias {
                            let instr = bot.read().await.get_prefix();
                            if inpt == String::from(instr) + alias.as_str() {
                                confirmed_bot_command = true;
                            }
                        }

                        if confirmed_bot_command {
                            botlog::debug(
                                format!("Confirmed bot command ; Msg : {}", msg.message_text)
                                    .as_str(),
                                Some("BotInstance > listener_main_prvmsg()".to_string()),
                                // Some(&msg),
                                Some(msg),
                            );

                            let botlock = bot.read().await;
                            let id = botlock.get_identity();

                            // [x] Check first if the Module for that Given Command is Enabled or Disabled on the given Channel
                            let modmgr = Arc::clone(&botlock.botmodules);
                            let modstatus = modmgr.modstatus(
                                c.module.clone(), 
                                Channel(msg.channel_login.to_string())).await;


                            if let StatusType::Disabled(a) = modstatus {

                                // [x] Should only respond if a BotAdmin , Mod , SupMod , BroadCaster
                                //    - Specifically it should respond only to those who may be able to enable the module

                                botlog::trace(
                                    &format!("Identified cmd is associated with Disabled Module : StatusLvl = {:?}", a),
                                    Some("BotInstance > listener_main_prvmsg()".to_string()),
                                    Some(msg),
                                );

                                
                                const OF_CMD_CHANNEL:Channel = Channel(String::new());

                                let elevated_access = {
                                    let mut idlock = id.write().await;
                                    let (permissability, _) = idlock
                                        .can_user_run_prvmsg(msg, 
                                            vec![
                                                identity::UserRole::BotAdmin,
                                                identity::UserRole::Mod(OF_CMD_CHANNEL),
                                                identity::UserRole::SupMod(OF_CMD_CHANNEL),
                                                identity::UserRole::Broadcaster,
                                            ])
                                        .await;
    
                                    permissability
                                };

                                if let Permissible::Allow = elevated_access {
                                    let botlock = bot.read().await;
                                    let outstr =
                                        format!("sadg Module is disabled : {:?}",a);
                                    botlock.botmgrs.chat.say_in_reply_to(msg, outstr).await;
                                } 

                                return;
                            };



                            let eval = {
                                let mut idlock = id.write().await;
                                let (permissability, chngrslt) = idlock
                                    .can_user_run_prvmsg(msg, c.required_roles.clone())
                                    .await;

                                (permissability, chngrslt)
                            };

                            botlog::trace(
                                "Checked if permissible",
                                Some("BotInstance > listener_main_prvmsg()".to_string()),
                                Some(msg),
                            );

                            let (eval, rolechange) = eval;

                            if let ChangeResult::Success(innerstr) = rolechange {
                                if innerstr
                                    .to_lowercase()
                                    .contains(&"Auto Promoted Mod".to_lowercase())
                                {
                                    botlog::notice(
                                        "Assigning Mod UserRole to Mod",
                                        Some("botinstance > listener_main_prvmsg()".to_string()),
                                        Some(msg),
                                    );

                                    let botlock = bot.read().await;
                                    let outstr =
                                        "o7 a Mod. I kneel to serve! pepeKneel ".to_string();
                                    botlock.botmgrs.chat.say_in_reply_to(msg, outstr).await;
                                }
                            }

                            match eval {
                                Permissible::Allow => {
                                    botlog::debug(
                                        "Executing as permissible",
                                        Some("BotInstance > listener_main_prvmsg()".to_string()),
                                        Some(msg),
                                    );

                                    let a = Arc::clone(&bot);
                                    c.execute(a, msg.clone()).await;

                                    botlog::trace(
                                        "exit out of execution",
                                        Some("BotInstance > listener_main_prvmsg()".to_string()),
                                        // Some(&msg),
                                        Some(msg),
                                    );
                                }

                                Permissible::Block => {
                                    botlog::info(
                                        "User Not allowed to run command",
                                        Some("BotInstance > listener_main_prvmsg()".to_string()),
                                        Some(msg),
                                    );
                                }
                            };
                        }
                    }

                    crate::core::botmodules::BotAction::L(l) => {
                        
                        let botlock = bot.read().await;
                        // let id = botlock.get_identity();

                        // [x] Check first if the Module for that Given Command is Enabled or Disabled on the given Channel
                        let modmgr = Arc::clone(&botlock.botmodules);
                        let modstatus = modmgr.modstatus(
                            l.module.clone(), 
                            Channel(msg.channel_login.to_string())).await;


                        if let StatusType::Disabled(a) = modstatus {

                            // [x] Should only respond if a BotAdmin , Mod , SupMod , BroadCaster
                            //    - Specifically it should respond only to those who may be able to enable the module

                            botlog::trace(
                                &format!("Identified listener is associated with Disabled Module : StatusLvl = {:?}", a),
                                Some("BotInstance > listener_main_prvmsg()".to_string()),
                                Some(msg),
                            );

                        } else {
                            let a = Arc::clone(&bot);
                            l.execute(a, msg.clone()).await;
                        }

                    }

                    _ => (),
                };
            }
        }

        botlog::trace(
            "End of Separate Listener Main prvmsg",
            Some("BotInstance > listener_main_prvmsg()".to_string()),
            Some(msg),
        );

        Log::flush();
    }
}

// ======================================
// ======================================
// ======================================
// ======================================

// UNIT TEST MODULES

// #[cfg(test)]
// mod tests {
//     fn always() {
//         assert_eq!(1, 1);
//     }
// }