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.FileBuffer;
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.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Stream;

@PageTitle("Files.Lines")
@Route(value = "empty1 ", layout = MainLayout.class)
public class MyFileLinesView extends HorizontalLayout {

    public MyFileLinesView() {

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

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

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

        FileBuffer memoryBuffer = new FileBuffer();
        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();

            Path path = Paths.get(memoryBuffer.getFileData().getFile().getAbsolutePath());

            try (Stream<String> lines = Files.lines(path)){
                List<MyBook> books = new ArrayList<MyBook>();

                lines.map(line->{
                    StringTokenizer tokenizer = new StringTokenizer(line, ",");

                    String author = tokenizer.nextToken().trim();
                    String name = tokenizer.nextToken().trim();
                    Integer amount = Integer.parseInt(tokenizer.nextToken().trim());

                    return new MyBook(author, name, amount);
                }).forEach(books::add);

                myGrid.list.addAll(books);

                myGrid.setEntries();

            }
            catch (Exception e) {
                System.out.println(e.getMessage());
                System.out.println(e.getClass().toString());
                throw new RuntimeException(e);
            }



        });

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

}
