use config;
use std::thread;
use nyaa::Nyaa;
use message_handler::{MessageHandlerBuilder,MessageHandler};
use colors;
use lib::log::Logger;
use lib::connection::Connection;
use lib::commands::Commands;
use std::sync::{Arc,Mutex,mpsc};

pub struct Irc{
    con: Connection,
}

impl Irc{
    pub fn new(con: Connection)->Irc{
        Irc{
            con
        }
    }
    pub fn start(&mut self)->bool

}

{
        let mut logger = match Logger::new("logs.txt"){
            Ok(l) =>l,
            Err(_) =>return false,
        };


        let cd = match config::ConfigData::new("config.json"){
            Ok(a) =>a,
            Err(err) =>{
                match err{
                    config::ConfigErr::Parse=>{logger.add("Config Parse Error");},
                    config::ConfigErr::Read=>{logger.add("Config Read Error");},
                    config::ConfigErr::Open=>{logger.add("Config Open Error");},
                }
                return false
            }
        };
        self.con.login(&cd.username,&cd.password);
        self.con.join_channels(&cd.channels);
        self.con.enable_tags();
        self.con.enable_whispers();
        self.con.set_char_limit(175);

        let mut commands = match Commands::new(){
            Ok(a) =>a,
            Err(_) =>{
                logger.add("Could not connect to redis");
                return false
            }
        };
        if commands.add_channels(&cd.channels).is_err(){
            logger.add("Could not load commands from redis");
        }
        let mut sock = match self.con.socket_clone(){
            Ok(a) =>a,
            Err(_) =>{
                logger.add("Could not clone the socket. Error: ");
                return false
            }
        };
        let (tx, rx) = mpsc::channel();

        let delay = cd.nyaa.delay;
        let channels = cd.channels;
        thread::spawn(move || {
            if let Ok(nyaa) = Nyaa::new(None){
                nyaa.start(&mut sock,channels,delay,tx)
            }
        });

        let animes = Arc::new(Mutex::new(Vec::new()));
        let animes_clone = animes.clone();
        let (dc_sender,dc_receiver) = mpsc::channel();
        thread::spawn(move || {
            loop{
                match rx.recv(){
                    Ok(a) => {
                        *animes.lock().unwrap() = a;
                        match dc_receiver.try_recv(){
                            Ok(_)=>break,
                            Err(mpsc::TryRecvError::Empty)=>{},
                            Err(mpsc::TryRecvError::Disconnected)=>break
                        }
                    }
                    Err(_) =>{
                        break
                    }
                }
            }
        });

        let colors = match colors::Color::new("colors.txt"){
            Ok(a) =>a,
            Err(_) =>{
                logger.add("Could not load colors file");
                return false
            }
        };

        let mut message_handler = MessageHandlerBuilder::new(&mut self.con,&animes_clone)
            .commands(commands)
            .logger(logger)
            .colors(colors)
            .admins(cd.admins)
            .build();
        loop{
            if !message_handler.on_new_message(){
                if dc_sender.send("need reconnect").is_err(){
                    println!("dc receiver disconnected")
                }
                break;
            }
        }
        return false;
    }