package edu.fiu;

import edu.fiu.repositories.SessionRepository;
import edu.fiu.repositories.UserRepository;

import org.jooby.Response;
import org.jooby.Request;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import edu.fiu.models.Session;

public class Authorize {

    /**
     * Checks if the user is authenticated for each request
     * 
     * @param req
     * @param rsp
     * @param sessions
     * @param users
     */
    public static void checkSession(Request req, Response rsp, SessionRepository sessions, UserRepository users) {

        String path = req.path();
        String[] parts = path.split("/");

        // Error
        if (parts.length == 0)
            return;

        // Login attempt
        if (path.equals("/api/session")) {
            //System.out.println("Login attempt");
            return;
        }

        // Ignore file requests (eg picture.jpeg)
        String fileName = parts[parts.length - 1];
        if (fileName.split("\\.").length > 1) { // SP5 check greater than 1 instead of not equal to zero
            return;
        }

        // gets the Authorization header value of the http requests
        List<String> header = req.header("Authorization").toList();
        //System.out.print("This is the header: ");
        //System.out.println(header);
        if (header.size() != 0) {
            try {
                String token = header.get(0).replace("Bearer ", "");
                Session s = sessions.get(token);

                // if session is not null, then the user is authorized
                if (s != null) {

                    // dateTime now
                    LocalDateTime now = LocalDateTime.now();
                    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                    try {
                        String formatDateTime = now.format(format);
                        sessions.updateSession(token, formatDateTime);
                        //System.out.println("Token exists and has been updated");
                    } catch (Exception ex) {
                        System.out.println("Unable to update time of existing token");
                        // do nothing
                    }
                    return;
                }

                else {
                    //System.out.println("Session is null");
                }

            } catch (Exception ex) {
                System.out.println(ex.getMessage());
            }
        }

        // If we made it here all auth failed - Throw 403 Unauthorized
        System.out.println("Authentication failed");
        rsp.status(403);
        rsp.end();
    }
}
