package com.example.application.views.MyFileUploader;

import com.example.application.MyBook.MyBook;
import com.example.application.MyGrid.MyGrid;
import com.example.application.views.MainLayout;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.notification.Notification;
import com.vaadin.flow.component.notification.NotificationVariant;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.tabs.Tab;
import com.vaadin.flow.component.tabs.Tabs;
import com.vaadin.flow.component.upload.receivers.MemoryBuffer;
import com.vaadin.flow.component.upload.Upload;
import com.vaadin.flow.router.PageTitle;
import com.vaadin.flow.router.Route;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.component.html.Div;
import static org.atmosphere.annotation.AnnotationUtil.logger;


import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.Scanner;

@PageTitle("FileScanner")
@Route(value = "empty", layout = MainLayout.class)
public class MyFileScannerView extends HorizontalLayout {

    public MyFileScannerView() {

        //Объявления
        MyGrid myGrid=new MyGrid();

        Button searchAuthor = new Button("Выполнить поиск");

        TextField currentAuthor = new TextField("Поиск по автору");
        TextField totalNumberOfBooks = new TextField("Общее количество книг");

        MemoryBuffer memoryBuffer = new MemoryBuffer();
        Upload uploader = new Upload(memoryBuffer);

        // Создаем вертикальное меню, связываем каждый пункт меню с компонентом
        Map<Tab, com.vaadin.flow.component.Component> tabsToComponents = new HashMap<>();

        Tab t1 = new Tab("Загрузить текстовый файл");
        Tab t2 = new Tab("Таблица");

        uploader.setAcceptedFileTypes(".txt");

        //неправильный файл
        uploader.addFileRejectedListener(event -> {
            String errorMessage = event.getErrorMessage();
            Notification notification = Notification.show(errorMessage, 5000,
                    Notification.Position.TOP_CENTER);
            notification.addThemeVariants(NotificationVariant.LUMO_ERROR);
            logger.info(errorMessage);
        });

        uploader.addSucceededListener(event -> {

            myGrid.list.clear();
            InputStream file = memoryBuffer.getInputStream();

            Scanner scanner = new Scanner(file);
            while (scanner.hasNextLine()) {
                String line = String.valueOf(scanner.nextLine());
                String [] data = line.split(",");
                myGrid.list.add(new MyBook(data[0], data[1], Integer.valueOf(data[2])));
            }
            scanner.close();
            myGrid.setEntries();
        });

        tabsToComponents.put(t1, uploader);

        VerticalLayout verticalLayout = new VerticalLayout();
        verticalLayout.add(myGrid.getGrid(),
                currentAuthor,
                totalNumberOfBooks,
                searchAuthor);
        tabsToComponents.put(t2, verticalLayout);


        //поиск книг автора
        searchAuthor.addClickListener(event -> {
                int amountOfBooks = 0;
                String searchedAuthor = currentAuthor.getValue();
                if (Objects.equals(searchedAuthor, "")){
                    for (MyBook obj: myGrid.list){
                        amountOfBooks += obj.getAmount();
                    }
                }
                for (MyBook obj: myGrid.list){
                    if (Objects.equals(obj.getAuthor(), searchedAuthor)) {
                        amountOfBooks += obj.getAmount();
                    }
                }
                totalNumberOfBooks.setValue(String.valueOf(amountOfBooks));
            }
        );

        Tabs tabs = new Tabs(t1, t2);
        tabs.setOrientation(Tabs.Orientation.VERTICAL);
        tabs.setHeight("500dp");
        tabs.setWidth("500dp");

        // Обрабатываем событие выбор пункта меню
        tabs.addSelectedChangeListener(event -> {
            tabsToComponents.values().forEach(component -> component.setVisible(false));
            tabsToComponents.get(tabs.getSelectedTab()).setVisible(true);
        });
        tabsToComponents.values().forEach(component -> component.setVisible(false));
        tabsToComponents.get(t1).setVisible(true);

        Div pages = new Div(uploader, verticalLayout);
        add(tabs, pages);
    }

}
