package pl.dmcs.springbootjsp_iwa.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import pl.dmcs.springbootjsp_iwa.model.Fibonacci;

import java.util.ArrayList;

@Controller
public class FibonacciController {

    @RequestMapping("/fibonacci")
    public String fibonacci(Model model) {
        Fibonacci fibonacci = new Fibonacci();
        model.addAttribute("fibonacci", fibonacci);
        return "fibonacci";
    }

    @RequestMapping(value = "/calculateFib.html", method = RequestMethod.POST)
    public String calculateFib(@ModelAttribute("fibonacci") Fibonacci fibonacci) {
        int result = calculate(fibonacci);
        System.out.printf("#%d Fibonacci number is %d\n", fibonacci.getIndex(), result);
        return "redirect:fibonacci";
    }

    private int calculate(Fibonacci fib) {
        ArrayList<Integer> seq = fib.getSequence();
        int index = fib.getIndex();
        seq.add(0);
        seq.add(1);
        for (int i = 2; i < index; i++) {
            seq.add(seq.get(seq.size() - 1) + seq.get(seq.size() - 2));
        }
        return seq.get(index - 1);
    }
}
