package org.hso.ecommerce.contoller;

import org.hso.ecommerce.db.CustomerRepository;
import org.hso.ecommerce.entities.Customer;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.Cookie;
import java.util.List;
import java.util.UUID;

public class Login {

    private final CustomerRepository customerRepo;

    @Autowired
    public Login(CustomerRepository customerRepo) {
        this.customerRepo = customerRepo;
    }

    public Cookie getLoginToken(Customer customer) {
        // do the login magic and get a loginToken
        System.out.println(customer.username);
        System.out.println(customer.password);

        List<Customer> customers = customerRepo.findByUsername(customer.username);

        if (customers.size() == 1 && (customers.get(0).username.equals(customer.username) && customers.get(0).password.equals(customer.password))) {
            System.out.println("The login data is valid");

            String loginToken = UUID.randomUUID().toString();

            // set the loginToken as session cookie
            return new Cookie("loginToken", loginToken);
        } else {
            System.out.println("The login data is invalid!");
            return null; // redirect so the input files get cleared, otherwise only pwd gets cleared
        }


    }
}
