package hozza.network.views.frontend;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.HashMap;

import com.vaadin.flow.component.AttachEvent;
import com.vaadin.flow.component.DetachEvent;
import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.html.H1;
import com.vaadin.flow.component.html.H2;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.router.RouteAlias;
import com.vaadin.flow.server.auth.AnonymousAllowed;

import org.springframework.beans.factory.annotation.Autowired;

import hozza.network.services.StatService;

@RouteAlias(value = "", layout = FrontendLayout.class)
@Route(value = "/", layout = FrontendLayout.class)
@PageTitle("Last Month Stats")
@AnonymousAllowed
public class Home extends VerticalLayout
{
    StatService mariaController;

    HashMap<Integer, TextField> mariaFields;

    ArrayList<PusherThread> asyncThread = new ArrayList<>();
    UI ui = UI.getCurrent();

    TextField mariaRelationCount = new TextField("[MariaDB] Total Viewed Count","Loading","Loading");
    TextField mariaStreamerCount = new TextField("[MariaDB] Streamer Tracked","Loading","Loading");
    TextField mariaRelationToday = new TextField("[MariaDB] Today Viewed Count","Loading","Loading");
    TextField mariaViewerCount = new TextField("[MariaDB] Total Unique Viewers","Loading","Loading");
    TextField mariaViewerToday = new TextField("[MariaDB] Today New Unique Viewers","Loading","Loading");

    @SuppressWarnings("SpringJavaAutowiredMembersInspection")
    @Autowired
    public Home(StatService mariaController)
    {
        this.mariaController = mariaController;
        this.mariaFields = new HashMap<>();
        this.mariaFields.put(0, mariaRelationCount);
        this.mariaFields.put(1, mariaStreamerCount);
        this.mariaFields.put(2, mariaRelationToday);
        this.mariaFields.put(3, mariaViewerCount);
        this.mariaFields.put(4, mariaViewerToday);

        H1 header = new H1("Database statistics");
        header.getStyle().set("text-align", "center");
        
        ui.getLoadingIndicatorConfiguration().setApplyDefaultTheme(false);
        this.addClassName("home");
        this.setSizeFull();
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.CENTER);
        
        this.add(header);
        
        HorizontalLayout wrapper = new HorizontalLayout();
        wrapper.addClassName("flex-container");
        wrapper.setSizeFull();
        wrapper.setAlignItems(Alignment.CENTER);
        wrapper.setJustifyContentMode(JustifyContentMode.BETWEEN);
        VerticalLayout mariaColumn = new VerticalLayout();

        mariaColumn.addClassName("flex-item");
        mariaColumn.setSizeFull();
        mariaColumn.setAlignItems(Alignment.CENTER);
        mariaColumn.setJustifyContentMode(JustifyContentMode.CENTER);

        H2 mariaHeader = new H2("MariaDB data");
        mariaHeader.getStyle().set("text-align", "center");

        mariaColumn.add(mariaHeader);

        this.mariaFields.values().forEach(val -> 
        {
            val.setReadOnly(true);
            val.addClassName("flex-input");
            mariaColumn.add(val);
        });

        wrapper.add(mariaColumn);
        this.add(wrapper);
    }

    @Override
    protected void onDetach(DetachEvent detachEvent) 
    {
        asyncThread.forEach(Thread::interrupt);
        asyncThread.clear();
    }
    
    @Override
    protected void onAttach(AttachEvent attachEvent) 
    {
        for(int i = 0; i < 5; i++)
        {
;            asyncThread.add(new PusherThread(ui, i, this.mariaController, mariaFields));
        }
        asyncThread.forEach(Thread::start);
    }

    private static class PusherThread extends Thread
    {
        private final UI ui;
        private final int parameter;
        private final StatService service;
        private final HashMap<Integer, TextField> map;

        public PusherThread(UI ui, int parameter, StatService service, HashMap<Integer, TextField> map)
        {
            this.ui = ui;
            this.parameter = parameter;
            this.service = service;
            this.map = map;
        }
        @Override
        public void run()
        {
            final int count = switch (parameter) {
                case 0 -> service.getRelationCount();
                case 1 -> service.getStreamerCount();
                case 2 -> service.getRelationCountToday();
                case 3 -> service.getViewerCount();
                case 4 -> service.getViewerCountToday();
                default -> 0;
            };
            ui.access(() -> {
                DecimalFormatSymbols symbols = new DecimalFormatSymbols();
                DecimalFormat format = new DecimalFormat();
                symbols.setGroupingSeparator(' ');
                format.setDecimalFormatSymbols(symbols);
                format.setGroupingSize(3);
                map.get(parameter).setValue(format.format(count));
                ui.push();
            });
        }
    }
}
