package hozza.network.views.frontend;

import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.DetachEvent;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.html.Div;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.server.auth.AnonymousAllowed;
import hozza.network.services.StatService;
import hozza.network.views.frontend.components.WatchingDayOfWeekChart;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;

@Route(value = "streamers", layout = FrontendLayout.class)
@PageTitle("Streamer Stats")
@AnonymousAllowed
public class StreamerStats extends VerticalLayout
{
    StatService mariaController;
    ArrayList<PusherThread> asyncThread = new ArrayList<>();
    UI ui = UI.getCurrent();

    H1 h1 = new H1("LOADING!");
    Div chartDiv = new Div();
    @SuppressWarnings("SpringJavaAutowiredMembersInspection")
    @Autowired
    public StreamerStats(StatService mariaController)
    {
        this.mariaController = mariaController;
        setWidth("100%");
        add(h1);
        add(chartDiv);
    }

    @Override
    protected void onDetach(DetachEvent detachEvent)
    {
        asyncThread.forEach(Thread::interrupt);
        asyncThread.clear();
    }

    @Override
    protected void onAttach(AttachEvent attachEvent)
    {
        asyncThread.add(new PusherThread(ui, this, this.mariaController));
        asyncThread.forEach(Thread::start);
    }

    private static class PusherThread extends Thread
    {
        private final UI ui;
        private final StreamerStats stats;
        private final StatService service;


        public PusherThread(UI ui, StreamerStats stats, StatService service)
        {
            this.ui = ui;
            this.stats = stats;
            this.service = service;
        }
        @Override
        public void run()
        {
            var data = this.service.getWatchingDayOfWeek();
            ui.access(() -> {
                WatchingDayOfWeekChart chartTemplate = new WatchingDayOfWeekChart(data);
                chartTemplate.setWidth("100%");
                chartTemplate.setHeight("80vh");
                stats.chartDiv.setWidth("100%");
                stats.chartDiv.add(chartTemplate);
                stats.remove(stats.h1);
                ui.push();
            });
        }
    }
}
