package com.example.FinanceTracker.Controllers;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import com.example.FinanceTracker.Models.Transaction;
import com.example.FinanceTracker.Repo.CategoriesRepo;
import com.example.FinanceTracker.Services.TransactionService;

@Controller
public class AddTransaction {

    @Autowired
    private TransactionService transactionService;

    @Autowired
    private CategoriesRepo categoriesRepo;

    @GetMapping("/addTransaction")
    public String addTransaction(Model model) {

        model.addAttribute("transaction", new Transaction());

        List<String> categoriesNames = categoriesRepo.findAllCategoryNames();
        model.addAttribute("categories", categoriesNames);

        // footer
        model.addAttribute("footerDetails", "Copyright © FinanceTracker " + LocalDate.now().getYear());

        return "add-transaction";
    }

    @PostMapping("/addTranaction")
    public String addNewTranactions(@ModelAttribute Transaction transaction, Model model) {

        transactionValidation(transaction);

        transactionService.save(transaction);

        // Set Category Dropdown menu
        List<String> categoriesNames = categoriesRepo.findAllCategoryNames();
        model.addAttribute("categories", categoriesNames);

        return "add-transaction";

    }

    private void transactionValidation(Transaction transaction) {

        // Set Balance
        BigDecimal balance = new BigDecimal(transactionService.getLatestBalance());
        transaction.setBalance(
                balance.add(transaction.getMoneyIn())
                        .add(transaction.getFee()).setScale(2, RoundingMode.HALF_UP));

        // Set Money In/Money Out
        if (transaction.getMoneyIn().compareTo(BigDecimal.ZERO) > 0) {
            transaction.setMoneyOut(new BigDecimal(0));
        } else if ((transaction.getMoneyIn().compareTo(BigDecimal.ZERO) < 0)) {
            transaction.setMoneyOut(transaction.getMoneyIn());
            transaction.setMoneyIn(new BigDecimal(0));
        }

        // Handle Fees
        if (transaction.getFee() == null) {
            transaction.setFee(new BigDecimal(0));
        }

    }

}
