package com.example.csbananasite.components;



import com.example.csbananasite.model.StatistikaUser;
import com.example.csbananasite.repo.StatistikaUserRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;

@Component
public class GrafickJson {

    @Autowired
    private StatistikaUserRepo statistikaUserRepo;

    public String generate() {
        ArrayList<Double> xData = new ArrayList<>();
        ArrayList<Double> yData = new ArrayList<>();

        Iterable<StatistikaUser> allPosts = statistikaUserRepo.findAll();

        // Iterate over the records and populate xData and yData
        for (StatistikaUser post : allPosts) {
            xData.add(Double.valueOf(post.getData()));
            yData.add(Double.valueOf(post.getKolvo()));
        }

        return generateJSON(xData, yData);
    }

    private String generateJSON(ArrayList<Double> xData, ArrayList<Double> yData) {
        StringBuilder sb = new StringBuilder();
        sb.append("{ \"x\": [");
        for (Double x : xData) {
            sb.append(x).append(", ");
        }
        sb.delete(sb.length() - 2, sb.length()).append("], \"y\": [");
        for (Double y : yData) {
            sb.append(y).append(", ");
        }
        sb.delete(sb.length() - 2, sb.length()).append("]}");
        return sb.toString();
    }
}
