package com.example.MeteoStarSpring.dop;

import com.example.MeteoStarSpring.models.Post;
import com.example.MeteoStarSpring.repo.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;

@Component
public class GrafickJson {

    @Autowired
    private PostRepository postRepository;

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

        // Получаем все ID
        Iterable<Post> allPosts = postRepository.findAll();
        for (Post post : allPosts) {
            xData.add(Double.valueOf(post.getId()));
        }

        // Получаем значения из базы по указанной строке
        Iterable<Post> filteredPosts = postRepository.findAll(); // Получаем все записи
        for (Post post : filteredPosts) {
            if (name_dannye.equals("temp")) {
                yData.add(post.getTemp());
            } else if (name_dannye.equals("vlashnost")) {
                yData.add(post.getVlashnost());
            } else if (name_dannye.equals("svet")) {
                yData.add(Double.valueOf(post.getSvet()));
            }
        }

        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();
    }
}
