mod git;
mod ite;

use actix_files::Files;
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder, Error, HttpRequest, HttpMessage};
use askama_actix::Template;
use actix_session::{Session, CookieSession};
use actix_web_httpauth::headers::authorization::{Authorization, Basic};
use actix_web::http::header::Header;
use actix_web_httpauth::middleware::HttpAuthentication;
use actix_web::dev::ServiceRequest;
use actix_web_httpauth::extractors::basic::{BasicAuth, Config};
use actix_web_httpauth::extractors::AuthenticationError;
use crate::git::{GitBrowseEntry, GitRepo, GitCommit, GitBrowseDir};
use actix_web::middleware::Logger;
use env_logger::Env;
use crate::ite::SuperIterator;
use std::ops::Add;
use std::path::{PathBuf, Path};
use serde::Deserialize;
use std::process::{Command, Stdio, Child};
use actix_web::http::{header, StatusCode};
use std::io;
use std::collections::HashMap;
use std::io::{Read, BufRead, Write, ErrorKind};
use futures::{StreamExt, TryStreamExt, future};
use actix_web::web::Buf;
use actix_web::http::header::IntoHeaderValue;

#[derive(Template)]
#[template(path = "hello.html")]
struct HelloTemplate<'a> {
    name: &'a str,
}

struct User {
    name : String,
}

struct Owner {
    name : String,
}

struct Repository {
    name : String,
    owner : Owner,
}

#[derive(Template)]
#[template(path = "git.html")]
struct GitMainTemplate<TS, ROOT>
where for <'a> &'a TS : IntoIterator<Item = &'a GitBrowseEntry>,
      for <'a> &'a ROOT : IntoIterator<Item = &'a (String, String)>,
{
    repo : Repository,
    browse : TS,
    root : ROOT,
    user_opt : Option<User>,
}

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Bonjour monde !")
}

#[get("/test")]
async fn hello_test() -> impl Responder {
    HttpResponse::Ok().body("Coucou")
}

#[get("/askama")]
async fn askama() -> impl Responder {
    let name : &str = "world";
    HelloTemplate { name }
}

#[get("/session")]
async fn hello_session(session : Session) -> impl Responder {
    // session.renew();
    match session.set("VieuxVy", 1) {
        Ok(_) => HttpResponse::Ok().body("Coucou\r\n"),
        Err(e) => HttpResponse::BadGateway().body("fail\r\n"),
    }

}

// #[get("/auth")]
async fn hello_auth(req : HttpRequest) -> impl Responder {
    match Authorization::<Basic>::parse(&req){
        Ok(auth) => HttpResponse::Ok().body(format!("Hello, {}!", auth.as_ref().user_id())),
        Err(e) => HttpResponse::Unauthorized().body("forbidden")
    }
}


#[derive(Deserialize)]
struct GitWebQ {
    commit: Option<String>,
    path: Option<String>,
}


#[get("/git/{owner}/{repo}.git")]
async fn git_main(web::Path((owner, reponame)): web::Path<(String, String)>, web::Query(GitWebQ{commit : commitnameopt, path : pathopt}) : web::Query<GitWebQ>) -> impl Responder {
    let commitname = match commitnameopt {
        None => {"master".to_string()}
        Some(s) => {s}
    };
    let rootname = match pathopt {
        None => {"/".to_string()}
        Some(s) => {s}
    };
    let repo = GitRepo::new();
    let path : Vec<(String, String)> = rootname.split("/").map_accum("/git/".to_string() + &owner + "/" + &reponame + "/" + &commitname, |str_ref, b| {
        let href = b + "/" + str_ref;
        ((str_ref.to_string(), href.clone()), href)
    }).collect();
    let commit = GitCommit::new(commitname);
    let root = GitBrowseDir::new(rootname);
    let browse = repo.browse(&commit, &root).await;
    let owner = Owner { name : owner};
    let repo = Repository {name : reponame, owner};
    let user = User { name : "Hubert".to_string()};
    GitMainTemplate { repo, browse : browse, root : path, user_opt : Some(user)}
}
//#[get("/git/{owner}/{repo}.git/{path:.*}")]
async fn git_proto(payload : web::Payload, web::Path((owner, reponame)): web::Path<(String, String)>, mut req: HttpRequest) -> io::Result<HttpResponse>{
    let mut cmd = Command::new("git");
    cmd.arg("http-backend");

    // Required environment variables
    cmd.env("REQUEST_METHOD", req.method().as_str());
    cmd.env("GIT_PROJECT_ROOT", "/home/hubert");
    cmd.env(
        "PATH_INFO",
        if req.path().starts_with('/') {
            req.path().to_string()
        } else {
            format!("/{}", req.path())
        },
    );
    cmd.env("REMOTE_USER", "");
    //cmd.env("REMOTE_ADDR", req.remote_addr().to_string());
    cmd.env("QUERY_STRING", req.query_string());
    cmd.env("CONTENT_TYPE", header(&req, header::CONTENT_TYPE));
    cmd.stderr(Stdio::inherit())
        .stdout(Stdio::piped())
        .stdin(Stdio::piped());
    let mut p: Child = cmd.spawn()?;
    //p.stdin.take().unwrap().write()
    let mut input = p.stdin.take().unwrap();
    payload.try_for_each(|bytes| {
        // println!("{:?}", bytes);
        input.write(bytes.bytes());
        future::ready(Ok(()))
    }).await;
    //io::copy(&mut req.take_payload(), &mut p.stdin.take().unwrap())?;
    // Parse the headers coming out, and the pass through the rest of the
    // process back down the stack.
    //
    // Note that we have to be careful to not drop the process which will wait
    // for the process to exit (and we haven't read stdout)
    let mut rdr = io::BufReader::new(p.stdout.take().unwrap());

    let mut headers = HashMap::new();
    for line in rdr.by_ref().lines() {
        let line = line?;
        if line == "" || line == "\r" {
            break;
        }

        let mut parts = line.splitn(2, ':');
        let key = parts.next().unwrap();
        let value = parts.next().unwrap();
        let value = &value[1..];
        headers
            .entry(key.to_string())
            .or_insert_with(Vec::new)
            .push(value.to_string());
    }

    let status_code : u16 = {
        let line = headers.remove("Status").unwrap_or_default();
        // println!("{:?}", &line);
        let line = line.into_iter().next().unwrap_or_default();
        let parts : Vec<&str> = line.split(' ').collect();
        parts.into_iter().next().unwrap_or("").parse().unwrap_or(200)
    };
    // println!("{}", status_code);

    let statusCode = match StatusCode::from_u16(status_code) {
        Ok(v) => {Ok(v)}
        Err(ioe) => {Err(io::Error::new(ErrorKind::Other, "Invalid HTTP status code"))}
    };
    let mut builder = HttpResponse::build(statusCode?);
    for (name, vec) in headers.iter() {
        for value in vec {
            builder.header(name, value.clone());
        }
    }

    let mut body = Vec::new();
    rdr.read_to_end(&mut body)?;
    return Ok(builder.body(body));

}

fn header(req: &HttpRequest, name: header::HeaderName) -> &str {
    req.headers()
        .get(name)
        .map(|value| value.to_str().unwrap_or_default())
        .unwrap_or_default()
}

#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
    HttpResponse::Ok().body(req_body)
}

async fn manual_hello() -> impl Responder {
    HttpResponse::Ok().body("Hey there!\r\n")
}

#[get("/{id}/{name}/index.html")]
async fn index(web::Path((id, name)): web::Path<(u32, String)>) -> impl Responder {
    format!("Hello {}! id:{}", name, id)
}

async fn basic_auth_validator(req: ServiceRequest, credentials: BasicAuth) -> Result<ServiceRequest, Error> {
    let config = req
        .app_data::<Config>()
        .map(|data| data.clone())
        .unwrap_or_else(Default::default);
    match validate_credentials(credentials.user_id(), credentials.password().map(|s| s.trim())) {
        Ok(res) => {
            if res == true {
                Ok(req)
            } else {
                Err(AuthenticationError::from(config).into())
            }
        }
        Err(_) => Err(AuthenticationError::from(config).into()),
    }
}

fn validate_credentials(user_id: &str, user_password: Option<&str>) -> Result<bool, std::io::Error>
{
    if user_id.eq("karl") && user_password.eq(&Option::Some("password")) {
        return Ok(true);
    }
    return Err(std::io::Error::new(std::io::ErrorKind::Other, "Authentication failed!"));
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "actix_web=info");
    env_logger::from_env(Env::default().default_filter_or("info")).init();
    HttpServer::new(|| {
        let auth = HttpAuthentication::basic(basic_auth_validator);
        App::new()
            .wrap(Logger::default())
            // .wrap(Logger::new("%a %{User-Agent}i"))
            .wrap(CookieSession::signed(&[0; 32]).secure(false))
            .service(hello)
            .service(echo)
            .service(hello_test)
            .service(index)
            .service(askama)
            .service(git_main)
            .service(hello_session)
            //.service(git_proto)
            // .service(
            //     web::scope("/auth")
            //         .wrap(auth)
            //         .route("/", web::get().to(hello_auth))
            // )
            .service(
                web::resource("/auth")
                    .wrap(auth)
                    .route(web::get().to(hello_auth))
            )
            .service(
                web::resource("/git/{user}/{repo}.git/{path:.*}")
                    .route(web::route().to(git_proto))
            )
            .service(
                Files::new("/static", "static")
                    .use_last_modified(true)
                    .use_etag(true)
                    // .show_files_listing()
            )
            .route("/hey", web::get().to(manual_hello))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
