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::BotAR;
use crate::core::botmodules::ModulesManager;
use crate::core::identity::{IdentityManager, Permissible};

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 struct Channel(pub String);

use super::bot_actions::ExecBodyParams;
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 * 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 {

                 
                botlog::trace(
                    format!(
                        "[TRACE][ServerMessage] > {:?}",
                       message
                        )
                    .as_str(),
                    Some("BotInstance > runner()".to_string()),
                    None,
                );


                match message {
                    ServerMessage::Notice(msg) => {
                        botlog::notice(
                            format!("NOTICE : (#{:?}) {}", msg.channel_login, msg.message_text)
                                .as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                        Log::flush();
                    }
                    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),
                        );

                        
                        botlog::trace(
                            format!(
                                "[TRACE][Twitch Chat > {}] > {}: {:?}",
                                msg.channel_login, msg.sender.name, msg
                            )
                            .as_str(),
                            Some("BotInstance > runner()".to_string()),
                            Some(&msg),
                        );
                        Log::flush();

                        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,
                        );
                        Log::flush();
                    }
                    ServerMessage::Join(msg) => {
                        botlog::notice(
                            format!("JOINED: {}", msg.channel_login).as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                        Log::flush();
                    }
                    ServerMessage::Part(msg) => {
                        botlog::notice(
                            format!("PARTED: {}", msg.channel_login).as_str(),
                            Some("BotInstance > runner()".to_string()),
                            None,
                        );
                        Log::flush();
                    }
                    _ => {}
                };
                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)

                            
        /*
            [ ] What we should do instead is : 
            1. Check if the message is related to a Reply (so we know how many arguments we should skip)
            2. If a reply, skip the first argument
        */

        let mut msgiter= msg
            .message_text
            .split(' ');

        let arg1 = msgiter.next();
        let arg2 = msgiter.next();
        
        let reply = if let Some(Some(replyid)) = msg.source.tags.0.get("reply-thread-parent-msg-id") {
                Some(replyid)
            } else { None }
            ;

        
        let inpt = match reply {
            None => {  // Regular message, use the first arg as the command
                match arg1 {
                    None => return, // return if no argument found
                    Some(a) => a,
                }
            },
            Some(_) => {
                match arg2 { // A reply message, use the 2nd arg as the command
                    None => return, // return if no argument found
                    Some(a) => a,
                }
            }, 
        };

        
        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 {

                let act_clone = Arc::clone(a);

                match &(*act_clone.read().await) {
                    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),
                        );

                        

                        // [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),
                                );

                                
                                let botclone = Arc::clone(&bot);
                                let botlock = botclone.read().await;
                                let id = botlock.get_identity();
                                let id = Arc::clone(&id);
                                let idlock = id.read().await; // <-- [ ] 03.24 - seems to work
                                let user_roles = idlock.getspecialuserroles(
                                    msg.sender.name.clone(), 
                                    Some(Channel(msg.channel_login.clone()))
                                ).await;


                                botlog::trace(
                                    &format!("For Disabled Command Evaluating User Roles {:?}", user_roles),
                                    Some("BotInstance > listener_main_prvmsg()".to_string()),
                                    Some(msg),
                                );

                                // Only respond to those with th ebelow User Roles

                                let outstr =
                                format!("sadg Module is disabled : {:?}",a);

                            
                                let params = ExecBodyParams {
                                    bot : Arc::clone(&bot),
                                    msg : (*msg).clone(),
                                    parent_act : Arc::clone(&act_clone),
                                };

                                // When sending a BotMsgTypeNotif, send_botmsg does Roles related validation as required

                                botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
                                    outstr
                                    ),
                                params,
                                ).await;

                                return;
                            };

                            botlog::trace(
                                "ACQUIRING WRITE LOCK : ID",
                                Some("BotInstance > listener_main_prvmsg()".to_string()),
                                Some(msg),
                            );


                            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();

                                    
                                    let params = ExecBodyParams {
                                        bot : Arc::clone(&bot),
                                        msg : (*msg).clone(),
                                        parent_act : Arc::clone(&act_clone),

                                    };

                                    botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
                                        outstr.to_string()
                                        ),
                                    params.clone(),
                                    ).await;

                                }

                                if innerstr
                                    .to_lowercase()
                                    .contains(&"Auto Promoted VIP".to_lowercase())
                                {
                                    botlog::notice(
                                        "Assigning VIP UserRole to VIP",
                                        Some("botinstance > listener_main_prvmsg()".to_string()),
                                        Some(msg),
                                    );

                                    let botlock = bot.read().await;
                                    let outstr =
                                        "❤️ a VIP - love ya!".to_string();

                                    
                                    let params = ExecBodyParams {
                                        bot : Arc::clone(&bot),
                                        msg : (*msg).clone(),
                                        parent_act : Arc::clone(&act_clone),

                                    };

                                    botlock.botmgrs.chat.send_botmsg(super::chat::BotMsgType::Notif(
                                        outstr.to_string()
                                        ),
                                    params.clone(),
                                    ).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(ExecBodyParams { 
                                        bot : a, 
                                        msg : msg.clone() ,
                                        parent_act : Arc::clone(&act_clone),
                                    }).await;

                                    botlog::trace(
                                        "exit out of execution",
                                        Some("BotInstance > listener_main_prvmsg()".to_string()),
                                        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;

                        // [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(ExecBodyParams { 
                                bot : a, 
                                msg : msg.clone() , 
                                parent_act : Arc::clone(&act_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);
//     }
// }