#![allow(unused)]
use actix::{Actor, StreamHandler};
use actix_files::{Files, NamedFile};
use actix_form_data::{Error, Field, Value};
use actix_identity::Identity;
use actix_identity::{CookieIdentityPolicy, IdentityService};
use actix_multipart::Multipart;
use actix_web::{
    cookie::Cookie, get, http, middleware, post, web, web::Data, web::Form, web::Path as Pathweb,
    App, HttpRequest, HttpResponse, HttpServer, Responder,
};
use actix_web_actors::ws;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::{fs::*, default};
use std::path::*;
use std::process::Command;
use tera::{Context, Tera};

#[macro_use]
extern crate diesel;
use diesel::prelude::*;

pub mod schema;
pub mod models;
// use models::{User, Project, Entity};

use walkdir::{DirEntry, WalkDir};

mod response;
mod util;
use util::*;
// use response::MyError;

use futures_util::TryStreamExt as _;
use std::io::Write;
use tempfile::tempfile;
use uuid::Uuid;

use std::fs::File;
use std::io::{self, prelude::*, BufReader};

#[get("/")]
async fn index(req: HttpRequest, tmpl: Data<Tera>, id: Identity) -> impl Responder {
    let mut context = Context::new();
    if let Some(val) = req.peer_addr() {
        println!("Address {:?}", &val.ip());
        context.insert("ip", &format!("{:?}", &val.ip()));
    };
    response::template(tmpl, "index.html.twig", &context)
}

async fn not_found(req: HttpRequest, tmpl: Data<Tera>, id: Identity) -> impl Responder {
    let context = Context::new();
    response::just_404(tmpl)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        let tera = Tera::new(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/**/*")).unwrap();
        let mut folder_static = "static/";
        App::new()
            .app_data(Data::new(tera))
            .wrap(IdentityService::new(
                CookieIdentityPolicy::new(&[0; 32])
                    .name("maps360")
                    .secure(true)
                    .max_age_secs(60 * 60 * 24 * 7), // 1week
            ))
            .wrap(middleware::Logger::default())
            .service(index)
            .service(Files::new("/static", folder_static))
            .default_service(web::route().to(not_found))
    })
    .workers(8)
    .bind(("0.0.0.0", 80))?
    .run()
    .await
}