use std::sync::Arc;
use axum::{
    //extract::{self,Request,Query},
    http::{
//        StatusCode,
        Uri,
        header::HeaderMap,// HeaderValue},
    },
//    Json,
    routing::get,
    Extension,
    extract::ConnectInfo,
    response::{IntoResponse,Response},
//    http::Request, handler::HandlerWithoutStateExt, http::StatusCode, routing::get, Router,    
    Router,
};
use tower_cookies::Cookies;

use crate::{
    route,
    defs::{
        AppDBs,
        Random,
        ReqHandler,
        ReqHeaderMap,
        AppConnectInfo,
    },
    handlers::get_auth_state,
};

pub fn pages_router_handlers() -> Router {
    async fn page_handler(
        //req: Request,
        header: HeaderMap,
        uri: Uri,
        Extension(app_dbs): Extension<Arc<AppDBs>>,
        Extension(cookies): Extension<Cookies>,
        Extension(random): Extension<Random>,
        ConnectInfo(app_connect_info): ConnectInfo<AppConnectInfo>,
        axum::extract::Path(name): axum::extract::Path<String>,
        //auth_state: AuthState,
    ) -> Response {
        // if let Some(cookie_value) = get_cookie(&req) {
        //     println!("cookie_value: {}",&cookie_value.to_string());
        //     // TODO check value 
        // }
        //let  has_cookie: bool;
        // dbg!(&auth_state.session);
        // 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,
            "page_handler"
        );
        // if let Some(a) = auth_state {
        //     println!("Auth State from root");
        // }
        // let uri_path = format!("{}",&uri.path().to_string());
        // dbg!("uri: {}",&uri_path);
        req_handler.prepare_response();
        req_handler.context.insert("with_menu", "1");
        let tpl_name = if name.contains(".html") {
            name.replace(".html","")
        } else {
            name
        };
        let result = req_handler.render_template(&format!("pages/{}.html.j2",&tpl_name), &tpl_name);
        // 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()
    //     "Hello, World!"
    }
    route("/page/:name", get(page_handler))
}