use std::sync::Arc;
use axum::{
    http::{
        Uri,
        header::HeaderMap,
    },
    routing::get,
    Extension,
    extract::ConnectInfo,
    response::{IntoResponse,Response},
    Router,
};
use tower_cookies::Cookies;

use crate::{
    route,
    defs::{
        AppDBs,
        ReqHandler,
        ReqHeaderMap,
        Random,
        AppConnectInfo,
    },
    handlers::{
        get_auth_state,
        users_login_router_handlers,
        users_password_router_handlers,
        users_invite_router_handlers,
        users_settings_router_handlers,
    },
};
pub fn users_router_handlers() -> Router {
    async fn main_handler(
        header: HeaderMap,
        uri: Uri,
        Extension(app_dbs): Extension<Arc<AppDBs>>,
        Extension(random): Extension<Random>,
        Extension(cookies): Extension<Cookies>,
        ConnectInfo(app_connect_info): ConnectInfo<AppConnectInfo>,
    ) -> Response {
        // if let Some(cookie_value) = get_cookie(&req) {
        //     println!("cookie_value: {}",&cookie_value.to_string());
        //     // TODO check value 
        // }
        //let  has_cookie: bool;
        // if auth_state.user.is_none() {
        //     eprintln!("No user found in session");
        // }
        let auth_state = get_auth_state(true, &cookies, &app_dbs).await;
        //    has_cookie=true;
            // TODO check value
            // let sid: String = format!("{}",&auth_state.sid());
            // println!("auth_sid: {}",&sid);
            // println!("id: {}",&auth_state.id());
            // println!("is_expired: {}",&auth_state.ses_expired());
            // println!("is_destroyed: {}",&auth_state.ses_destroyed());
            // println!("validate: {}",&auth_state.ses_validate());
            // let _u = &auth_state.user;
        let mut req_handler = ReqHandler::new(
            ReqHeaderMap::new(header, &format!("{}",&uri.path().to_string()), &app_connect_info),
            &app_dbs,
            &uri,
            &auth_state,
            &random,
            "main_handler"
        );
        // if let Some(a) = auth_state {
        //     println!("Auth State from root");
        // }
        // let uri_path = format!("{}",&uri.path().to_string());
        req_handler.prepare_response();
        req_handler.context.insert("with_menu", "1");
        let result = if let Some(tpl) = app_dbs.config.tpls.get("main") {
            req_handler.render_template(&tpl,"main")
        } else {
            String::from("main")
        };
        let _ = req_handler.trace_req(String::from("main request"));
        // if !has_cookie {
        //     let mut u128_pool = [0u8; 16];
        //     match random.lock() {
        //         Ok(mut r) => r.fill_bytes(&mut u128_pool),
        //         Err(e) => println!("Error random: {}",e),
        //     }
        //     let session_token = u128::from_le_bytes(u128_pool).to_string();
        //     let user_data = format!("{}|{}","jesus" ,"admin,dev");
        //     let result_store = SessionStoreDB::store_session_data(&session_token,&user_data,&app_dbs).await;
        //     println!("Rest store: {}",&result_store);
        //     let cookie = Cookie::build(SESSION_COOKIE_NAME, session_token.to_owned())
        //     //  .domain(domain)
        //         .path("/")
        //         .secure(true)
        //         .http_only(true)
        //         .finish();
        //     cookies.remove(Cookie::new(SESSION_COOKIE_NAME, ""));
        //     cookies.add(cookie);
        // }
        (
            req_handler.req_header.header,
            result.to_owned()
        ).into_response()
    }
    // async fn auto_handler(
    //     //req: Request,
    //     header: HeaderMap,
    //     uri: Uri,
    //     Extension(app_dbs): Extension<Arc<AppDBs>>,
    //     Extension(random): Extension<Random>,
    //     Extension(cookies): Extension<Cookies>,
    //     // _auth_state: AuthState,
    // ) -> Response {
    //     // if let Some(cookie_value) = get_cookie(&req) {
    //     //     println!("cookie_value: {}",&cookie_value.to_string());
    //     //     // TODO check value 
    //     // }
    //     let auth_state = get_auth_state(true, &cookies, &app_dbs).await;
    //     let has_cookie: bool;
    //     if let Some(cookie_value) = cookies.get(SESSION_COOKIE_NAME) {
    //         println!("cookie_value: {}",&cookie_value.to_string());
    //         //has_cookie=true;
    //         has_cookie=false;
    //         // TODO check value 
    //     } else {
    //         has_cookie=false;
    //     }
    //     // if let Some(a) = auth_state {
    //     //     println!("Auth State from root");
    //     // }
    //     let uri_path = format!("{}",&uri.path().to_string());
    //     let file =  "hello.html";
    //     let result = app_dbs.tera.render(&file, &app_dbs.context).unwrap_or_else(|e|{
    //         println!("Error render {}: {}",&file,e);
    //         String::from("")
    //     });
    //     /*
    //     if !has_cookie {
    //         let mut u128_pool = [0u8; 16];
    //         match random.lock() {
    //             Ok(mut r) => r.fill_bytes(&mut u128_pool),
    //             Err(e) => println!("Error random: {}",e),
    //         }
    //         let session_token = u128::from_le_bytes(u128_pool).to_string();
    //         let user_data = format!("{}|{}","jesus" ,"admin,dev");
    //         let result_store = SessionStoreDB::store_session_data(&session_token,&user_data,&app_dbs).await;
    //         println!("Rest store: {}",&result_store);
    //         let cookie = Cookie::build(SESSION_COOKIE_NAME, result_store)
    //         //  .domain(domain)
    //             .path("/")
    //             .secure(true)
    //             .http_only(true)
    //             .finish();
    //         cookies.remove(Cookie::new(SESSION_COOKIE_NAME, ""));
    //         cookies.add(cookie);
    //     }
    //    */
    //     (
    //         header,
    //         result.to_owned()
    //     ).into_response()
    // //     "Hello, World!"
    // }:1
    
    route("/", get(main_handler))
    //   .route("/auto", get(auto_handler))
        .merge(users_login_router_handlers())
        .merge(users_password_router_handlers())
        .merge(users_invite_router_handlers())
        .merge(users_settings_router_handlers())
}
