package org.hso.ecommerce.controller.intern.customers;

import org.hso.ecommerce.controller.intern.accounting.AccountingController;
import org.hso.ecommerce.controller.intern.accounting.AccountingController.ShortTemplateBookingResult;
import org.hso.ecommerce.entities.booking.Booking;
import org.hso.ecommerce.entities.shop.CustomerOrder;
import org.hso.ecommerce.entities.user.User;
import org.hso.ecommerce.repos.booking.BookingRepository;
import org.hso.ecommerce.repos.shop.CustomerOrderRepository;
import org.hso.ecommerce.repos.user.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("/intern/customers")
public class CustomersIndexController {

    @Autowired
    private BookingRepository bookingRepository = null;

    @Autowired
    private final CustomerOrderRepository customerOrderRepository = null;

    @Autowired
    private final UserRepository userRepository = null;

    @Autowired
    private AccountingController accountingController = null;

    @GetMapping("")
    public String internCustomers(Model model) {
        List<User> users = userRepository.findAll();

        model.addAttribute("users", users);

        return "intern/customers/index";
    }

    @GetMapping("/{id}")
    public String internCustomersId(Model model,
                                    @PathVariable("id") Long id,
                                    HttpServletResponse response,
                                    HttpServletRequest request
    ) {
        Optional<User> optUser = userRepository.findById(id);
        if (!optUser.isPresent()) {
            request.setAttribute("error", "Der User wurde nicht gefunden.");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return "error/404";
        }
        User user = optUser.get();
        model.addAttribute("user", user);

        List<CustomerOrder> orders = customerOrderRepository.getOrdersByUserId(id);
        model.addAttribute("orders", orders);

        List<Booking> bookings = bookingRepository.customerBookingsReverseChronologically(id);
        ShortTemplateBookingResult result = accountingController.buildShortTemplate(
                bookings,
                account -> account.userAccount != null && account.userAccount.id == id);
        model.addAttribute("balance", result.balance);
        model.addAttribute("bookings", result.bookings);

        return "intern/customers/id";
    }

    @PostMapping("/{id}/changeState")
    public String changeState(@PathVariable("id") Long id,
                              @RequestParam(value = "active", required = false) String active,
                              @RequestParam(value = "ma", required = false) String ma
    ) {
        User user = userRepository.findById(id).get();

        if (active == null)
            user.isActive = false;
        else
            user.isActive = true;

        if (ma == null)
            user.isEmployee = false;
        else
            user.isEmployee = true;

        userRepository.save(user);

        return "redirect:/intern/customers/" + id.toString();
    }

    @PostMapping("/{id}/resetPassword")
    public String resetPassword(@PathVariable("id") Long id,
                                @RequestParam("password") String password,
                                @RequestParam("password2") String password2,
                                HttpServletRequest request
    ) {
        if (!password.equals(password2)) {
            request.setAttribute("error", "Passwörter stimmen nicht überein!");
            return "intern/customers/id";
        }
        User user = userRepository.findById(id).get();
        if (!user.validatePassword(password)) {
            request.setAttribute("error", "Die Passwörter stimmen nicht mit dem Original überein!");
            return "intern/customers/id";
        }
        user.setPassword("12345");
        userRepository.save(user);
        request.setAttribute("info", "Passwort wurde auf 12345 geändert!");

        return "intern/customers/id";
    }
}

