package cz.kamma.kfmanager.ui;

import cz.kamma.kfmanager.model.FileItem;
import cz.kamma.kfmanager.service.FileOperations;

import javax.swing.*;
import java.awt.event.KeyEvent;
import java.awt.event.InputEvent;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.io.File;
import java.awt.Desktop;
import java.util.ArrayList;
import java.util.List;

/**
 * Dialog for searching files
 */
public class SearchDialog extends JDialog {
    
    private JComboBox<String> patternCombo;
    private JComboBox<String> contentPatternCombo;
    private JCheckBox recursiveCheckBox;
    private JCheckBox contentSearchCheckBox;
    private JCheckBox archiveSearchCheckBox;
    private JTable resultsTable;
    private ResultsTableModel tableModel;
    private JButton searchButton;
    private JButton cancelButton;
    private JButton viewButton;
    private JButton editButton;
    private JProgressBar statusProgressBar;
    private JLabel statusLabel;
    private volatile int foundCount = 0;
    private File searchDirectory;
    private volatile boolean searching = false;
    private cz.kamma.kfmanager.config.AppConfig config;
    
    public SearchDialog(Frame parent, File searchDirectory, cz.kamma.kfmanager.config.AppConfig config) {
        // Make the dialog modeless so it does not remain forced above other windows
        super(parent, "Search files", false);
        this.searchDirectory = searchDirectory;
        this.config = config;
        initComponents();
        // Allow the user to resize the search dialog
        setResizable(true);
        // sensible minimum size so layout remains usable
        setMinimumSize(new Dimension(480, 320));
        // Restore previous bounds if config present
        if (this.config != null) {
            try {
                this.config.restoreSearchDialogState(this);
            } catch (Exception ignore) {
                setSize(700, 500);
                setLocationRelativeTo(parent);
            }
        } else {
            setSize(700, 500);
            setLocationRelativeTo(parent);
        }
    }
    
    private void initComponents() {
        setLayout(new BorderLayout(10, 10));
        ((JComponent) getContentPane()).setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
        
        // Panel pro zadání kritérií
        JPanel searchPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        
        gbc.gridx = 0;
        gbc.gridy = 0;
        searchPanel.add(new JLabel("Hledat:"), gbc);
        
        gbc.gridx = 1;
        gbc.weightx = 1.0;
        // Pattern input is an editable combo box populated from history
        java.util.List<String> history = config != null ? config.getSearchHistory() : java.util.Collections.emptyList();
        javax.swing.DefaultComboBoxModel<String> historyModel = new javax.swing.DefaultComboBoxModel<>();
        for (String h : history) historyModel.addElement(h);
        patternCombo = new JComboBox<>(historyModel);
        patternCombo.setEditable(true);
        // start with an empty editor so the field is blank on open
        try {
            patternCombo.setSelectedItem("");
            patternCombo.getEditor().setItem("");
        } catch (Exception ignore) {}
        patternCombo.setToolTipText("Enter filename or pattern (* for any chars, ? for single char)");
        searchPanel.add(patternCombo, gbc);
        
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.gridwidth = 2;
        recursiveCheckBox = new JCheckBox("Include subdirectories", true);
        searchPanel.add(recursiveCheckBox, gbc);

        // Row for content text pattern
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.gridwidth = 1;
        searchPanel.add(new JLabel("Text:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 1.0;
        java.util.List<String> contentHistory = config != null ? config.getContentSearchHistory() : java.util.Collections.emptyList();
        javax.swing.DefaultComboBoxModel<String> contentHistoryModel = new javax.swing.DefaultComboBoxModel<>();
        for (String h : contentHistory) contentHistoryModel.addElement(h);
        contentPatternCombo = new JComboBox<>(contentHistoryModel);
        contentPatternCombo.setEditable(true);
        try { contentPatternCombo.setSelectedItem(""); contentPatternCombo.getEditor().setItem(""); } catch (Exception ignore) {}
        contentPatternCombo.setToolTipText("Text to search inside files");
        searchPanel.add(contentPatternCombo, gbc);

        gbc.gridy = 3;
        gbc.gridwidth = 2;
        contentSearchCheckBox = new JCheckBox("Search inside file contents", false);
        searchPanel.add(contentSearchCheckBox, gbc);

        gbc.gridy = 4;
        archiveSearchCheckBox = new JCheckBox("Search inside archives", false);
        archiveSearchCheckBox.setMnemonic(KeyEvent.VK_R);
        searchPanel.add(archiveSearchCheckBox, gbc);

        gbc.gridy = 5;
        JLabel pathLabel = new JLabel("Directory: " + searchDirectory.getAbsolutePath());
        pathLabel.setFont(pathLabel.getFont().deriveFont(Font.ITALIC));
        searchPanel.add(pathLabel, gbc);
        
        add(searchPanel, BorderLayout.NORTH);
        
        // Tabulka s výsledky
        tableModel = new ResultsTableModel();
        resultsTable = new JTable(tableModel);
        resultsTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        resultsTable.setFont(new Font("Monospaced", Font.PLAIN, 12));
        // let the table columns adjust when the dialog is resized
        resultsTable.setAutoResizeMode(JTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS);
        
        resultsTable.getColumnModel().getColumn(0).setPreferredWidth(400);
        resultsTable.getColumnModel().getColumn(1).setPreferredWidth(100);
        resultsTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        
        // Double-click pro otevření umístění
        resultsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent e) {
                if (e.getClickCount() == 2) {
                    openSelectedFile();
                }
            }
        });

        // Enable/disable view/edit buttons depending on selection
        resultsTable.getSelectionModel().addListSelectionListener(e -> {
            int sel = resultsTable.getSelectedRow();
            boolean ok = false;
            if (sel >= 0) {
                FileItem it = tableModel.getResult(sel);
                ok = it != null && !it.isDirectory() && !"..".equals(it.getName());
            }
            viewButton.setEnabled(ok);
            editButton.setEnabled(ok);
        });
        
    JScrollPane scrollPane = new JScrollPane(resultsTable);
    scrollPane.setBorder(BorderFactory.createTitledBorder("Výsledky"));
    add(scrollPane, BorderLayout.CENTER);
        
    // Status bar with progress and message
    statusLabel = new JLabel("Ready");
    statusProgressBar = new JProgressBar();
    statusProgressBar.setVisible(false);
    statusProgressBar.setIndeterminate(false);
    JPanel statusPanel = new JPanel(new BorderLayout(6, 6));
    statusPanel.setBorder(BorderFactory.createEmptyBorder(3, 3, 3, 3));
    statusPanel.add(statusLabel, BorderLayout.CENTER);
    statusPanel.add(statusProgressBar, BorderLayout.EAST);

    // Panel s tlačítky
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
        
    searchButton = new JButton("Hledat");
    searchButton.addActionListener(e -> performSearch());

    viewButton = new JButton("Zobrazit");
    viewButton.setEnabled(false);
    viewButton.addActionListener(e -> viewSelectedFile());

    editButton = new JButton("Upravit");
    editButton.setEnabled(false);
    editButton.addActionListener(e -> editSelectedFile());

    cancelButton = new JButton("Zavřít");
    cancelButton.addActionListener(e -> dispose());

    JButton openButton = new JButton("Otevřít umístění");
    openButton.addActionListener(e -> openSelectedFile());

    buttonPanel.add(searchButton);
    buttonPanel.add(viewButton);
    buttonPanel.add(editButton);
    buttonPanel.add(openButton);
    buttonPanel.add(cancelButton);
        
    // Compose bottom area: status bar above buttons
    JPanel bottomPanel = new JPanel(new BorderLayout());
    bottomPanel.add(statusPanel, BorderLayout.NORTH);
    bottomPanel.add(buttonPanel, BorderLayout.SOUTH);
    add(bottomPanel, BorderLayout.SOUTH);
        
        // Require explicit Enter to start search when choosing from history.
        // Bind Enter on the combo editor component so selecting an item from the
        // popup does not automatically trigger search until user confirms.
        java.awt.Component editorComp = patternCombo.getEditor().getEditorComponent();
        if (editorComp instanceof javax.swing.text.JTextComponent) {
            javax.swing.text.JTextComponent tc = (javax.swing.text.JTextComponent) editorComp;
            tc.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "confirmSearch");
            tc.getActionMap().put("confirmSearch", new AbstractAction() {
                @Override
                public void actionPerformed(java.awt.event.ActionEvent e) {
                    try {
                        // If the popup is visible, treat Enter as "confirm selection": fill editor and close popup
                        if (patternCombo.isPopupVisible()) {
                            Object sel = patternCombo.getSelectedItem();
                            if (sel != null) {
                                patternCombo.getEditor().setItem(sel.toString());
                            }
                            patternCombo.hidePopup();
                            return; // do not start search yet
                        }
                    } catch (Exception ignore) {}
                    // Popup not visible -> actual confirm to start search
                    performSearch();
                }
            });
        }

        // Same explicit-Enter behavior for content text pattern combo
        try {
            java.awt.Component contentEditorComp = contentPatternCombo.getEditor().getEditorComponent();
            if (contentEditorComp instanceof javax.swing.text.JTextComponent) {
                javax.swing.text.JTextComponent tc2 = (javax.swing.text.JTextComponent) contentEditorComp;
                tc2.getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "confirmSearchContent");
                tc2.getActionMap().put("confirmSearchContent", new AbstractAction() {
                    @Override
                    public void actionPerformed(java.awt.event.ActionEvent e) {
                        try {
                            if (contentPatternCombo.isPopupVisible()) {
                                Object sel = contentPatternCombo.getSelectedItem();
                                if (sel != null) contentPatternCombo.getEditor().setItem(sel.toString());
                                contentPatternCombo.hidePopup();
                                return;
                            }
                        } catch (Exception ignore) {}
                        performSearch();
                    }
                });
            }
        } catch (Exception ignore) {}

        // Alt+F focuses filename (pattern) input; Alt+T focuses content text input
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_F, InputEvent.ALT_DOWN_MASK), "focusFilename");
        getRootPane().getActionMap().put("focusFilename", new AbstractAction() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try {
                    java.awt.Component ed = patternCombo.getEditor().getEditorComponent();
                    if (ed != null) {
                        ed.requestFocusInWindow();
                        if (ed instanceof javax.swing.text.JTextComponent) {
                            ((javax.swing.text.JTextComponent) ed).selectAll();
                        }
                    }
                } catch (Exception ignore) {}
            }
        });
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_T, InputEvent.ALT_DOWN_MASK), "focusContentText");
        getRootPane().getActionMap().put("focusContentText", new AbstractAction() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                try {
                    // Toggle the content-search checkbox (on/off)
                    try {
                        if (contentSearchCheckBox != null) {
                            contentSearchCheckBox.setSelected(!contentSearchCheckBox.isSelected());
                        }
                    } catch (Exception ignore) {}

                    java.awt.Component ed = contentPatternCombo.getEditor().getEditorComponent();
                    if (ed != null) {
                        ed.requestFocusInWindow();
                        if (ed instanceof javax.swing.text.JTextComponent) {
                            ((javax.swing.text.JTextComponent) ed).selectAll();
                        }
                    }
                } catch (Exception ignore) {}
            }
        });

        // Alt+R toggles archive search
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_R, InputEvent.ALT_DOWN_MASK), "toggleArchiveSearch");
        getRootPane().getActionMap().put("toggleArchiveSearch", new AbstractAction() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                if (archiveSearchCheckBox != null) {
                    archiveSearchCheckBox.setSelected(!archiveSearchCheckBox.isSelected());
                }
            }
        });

        // Escape closes the dialog (and cancels ongoing search)
        getRootPane().registerKeyboardAction(e -> {
            searching = false;
            dispose();
        }, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_IN_FOCUSED_WINDOW);

        // F3 = view, F4 = edit when dialog is active
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_F3, 0), "viewResult");
        getRootPane().getActionMap().put("viewResult", new AbstractAction() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                viewSelectedFile();
            }
        });
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(
                KeyStroke.getKeyStroke(KeyEvent.VK_F4, 0), "editResult");
        getRootPane().getActionMap().put("editResult", new AbstractAction() {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent e) {
                editSelectedFile();
            }
        });
    }

    @Override
    public void dispose() {
        // Persist bounds before disposing
        try {
            if (config != null) {
                // also persist current pattern into history
                try {
                    Object it = patternCombo != null ? patternCombo.getEditor().getItem() : null;
                    String cur = it != null ? it.toString().trim() : null;
                    if (cur != null && !cur.isEmpty()) {
                        java.util.List<String> hist = new java.util.ArrayList<>(config.getSearchHistory());
                        hist.remove(cur);
                        hist.add(0, cur);
                        int max = 20;
                        while (hist.size() > max) hist.remove(hist.size() - 1);
                        config.saveSearchHistory(hist);
                    }
                } catch (Exception ignore) {}
                // also persist current content search pattern into history
                try {
                    Object cit = contentPatternCombo != null ? contentPatternCombo.getEditor().getItem() : null;
                    String ccur = cit != null ? cit.toString().trim() : null;
                    if (ccur != null && !ccur.isEmpty()) {
                        java.util.List<String> chist = new java.util.ArrayList<>(config.getContentSearchHistory());
                        chist.remove(ccur);
                        chist.add(0, ccur);
                        int maxc = 20;
                        while (chist.size() > maxc) chist.remove(chist.size() - 1);
                        config.saveContentSearchHistory(chist);
                    }
                } catch (Exception ignore) {}
                config.saveSearchDialogState(this);
                config.saveConfig();
            }
        } catch (Exception ignore) {}
        super.dispose();
    }
    
    /**
     * Provede vyhledávání
     */
    private void performSearch() {
        String namePat = "";
        try {
            Object it = patternCombo.getEditor().getItem();
            namePat = it != null ? it.toString().trim() : "";
        } catch (Exception ex) { namePat = ""; }

        String contentPat = "";
        try {
            Object cit = contentPatternCombo.getEditor().getItem();
            contentPat = cit != null ? cit.toString().trim() : "";
        } catch (Exception ex) { contentPat = ""; }

        final boolean isContentSearch = contentSearchCheckBox != null && contentSearchCheckBox.isSelected();

        if (isContentSearch) {
            if (contentPat.isEmpty()) {
                JOptionPane.showMessageDialog(this,
                        "Zadejte hledaný text",
                        "Chyba",
                        JOptionPane.WARNING_MESSAGE);
                return;
            }
        } else {
            if (namePat.isEmpty()) {
                JOptionPane.showMessageDialog(this,
                        "Zadejte hledaný vzor",
                        "Chyba",
                        JOptionPane.WARNING_MESSAGE);
                return;
            }
        }

        tableModel.clear();
        searchButton.setEnabled(false);
        searching = true;

    // Persist the chosen pattern into the appropriate history (most-recent-first)
        if (config != null) {
            try {
                if (isContentSearch) {
                    java.util.List<String> chist = new java.util.ArrayList<>(config.getContentSearchHistory());
                    chist.remove(contentPat);
                    chist.add(0, contentPat);
                    int max = 20;
                    while (chist.size() > max) chist.remove(chist.size() - 1);
                    config.saveContentSearchHistory(chist);
                    config.saveConfig();
                    // update content combo model
                    javax.swing.DefaultComboBoxModel<String> cm = (javax.swing.DefaultComboBoxModel<String>) contentPatternCombo.getModel();
                    cm.removeAllElements();
                    for (String s : chist) cm.addElement(s);
                    contentPatternCombo.setSelectedItem(contentPat);
                } else {
                    java.util.List<String> hist = new java.util.ArrayList<>(config.getSearchHistory());
                    hist.remove(namePat);
                    hist.add(0, namePat);
                    int max = 20;
                    while (hist.size() > max) hist.remove(hist.size() - 1);
                    config.saveSearchHistory(hist);
                    config.saveConfig();
                    // update combo model
                    javax.swing.DefaultComboBoxModel<String> m = (javax.swing.DefaultComboBoxModel<String>) patternCombo.getModel();
                    m.removeAllElements();
                    for (String s : hist) m.addElement(s);
                    patternCombo.setSelectedItem(namePat);
                }
            } catch (Exception ignore) {}
        }

        final String pattern = isContentSearch ? contentPat : namePat;
        final boolean searchArchives = archiveSearchCheckBox != null && archiveSearchCheckBox.isSelected();

    // Reset and show status
    foundCount = 0;
    statusLabel.setText("Searching...");
    statusProgressBar.setVisible(true);
    statusProgressBar.setIndeterminate(true);

    // Spustit vyhledávání v samostatném vlákně
        SwingWorker<Void, Object[]> worker = new SwingWorker<Void, Object[]>() {
            @Override
            protected Void doInBackground() throws Exception {
                if (isContentSearch) {
                    FileOperations.searchContents(searchDirectory, pattern, recursiveCheckBox.isSelected(), searchArchives, (file, virtualPath) -> {
                        if (!searching) return;
                        publish(new Object[]{file, virtualPath});
                    });
                } else {
                    FileOperations.search(searchDirectory, pattern, recursiveCheckBox.isSelected(), searchArchives, (file, virtualPath) -> {
                        if (!searching) return;
                        publish(new Object[]{file, virtualPath});
                    });
                }
                return null;
            }
            
            @Override
            protected void process(List<Object[]> chunks) {
                for (Object[] chunk : chunks) {
                    File file = (File) chunk[0];
                    String virtualPath = (String) chunk[1];
                    tableModel.addResult(new FileItem(file, virtualPath));
                    // update found count and status
                    foundCount++;
                    statusLabel.setText("Found " + foundCount + " — searching...");
                    // If this is the first found file, select it and focus the table
                    if (foundCount == 1) {
                        try {
                            resultsTable.setRowSelectionInterval(0, 0);
                            resultsTable.requestFocusInWindow();
                        } catch (Exception ignore) {}
                    }
                }
            }
            
            @Override
            protected void done() {
                searchButton.setEnabled(true);
                searching = false;
                // finalize status
                statusProgressBar.setIndeterminate(false);
                statusProgressBar.setVisible(false);
                try {
                    get();
                    statusLabel.setText("Done — found " + foundCount + " files");
                    if (tableModel.getRowCount() == 0) {
                        JOptionPane.showMessageDialog(SearchDialog.this, 
                                "Nebyly nalezeny žádné soubory", 
                                "Výsledek", 
                                JOptionPane.INFORMATION_MESSAGE);
                    }
                } catch (Exception e) {
                    statusLabel.setText("Error");
                    JOptionPane.showMessageDialog(SearchDialog.this, 
                            "Chyba při hledání: " + e.getMessage(), 
                            "Chyba", 
                            JOptionPane.ERROR_MESSAGE);
                }
            }
        };
        
        worker.execute();
    }
    
    /**
     * Otevře umístění vybraného souboru v exploreru
     */
    private void openSelectedFile() {
        int selectedRow = resultsTable.getSelectedRow();
        if (selectedRow >= 0) {
            FileItem item = tableModel.getResult(selectedRow);
            try {
                // Open location inside the application: show parent directory in the focused panel and select the file
                java.awt.Window w = SwingUtilities.getWindowAncestor(this);
                if (w instanceof MainWindow) {
                    MainWindow mw = (MainWindow) w;
                    mw.showFileInFocusedPanel(item.getFile());
                    dispose();
                    return;
                }
                // Fallback to opening in system explorer
                Desktop.getDesktop().open(item.getFile().getParentFile());
            } catch (Exception e) {
                JOptionPane.showMessageDialog(this, 
                        "Nepodařilo se otevřít umístění: " + e.getMessage(), 
                        "Chyba", 
                        JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    /**
     * Open the selected file in the internal viewer (read-only)
     */
    private void viewSelectedFile() {
        int sel = resultsTable.getSelectedRow();
        if (sel >= 0) {
            FileItem item = tableModel.getResult(sel);
            if (item != null && !item.isDirectory() && !"..".equals(item.getName())) {
                try {
                    Frame owner = (Frame) SwingUtilities.getWindowAncestor(this);
                    FileEditor viewer = new FileEditor(owner, item.getFile(), config, true);
                    viewer.addWindowListener(new java.awt.event.WindowAdapter() {
                        @Override
                        public void windowClosed(java.awt.event.WindowEvent e) {
                            resultsTable.requestFocusInWindow();
                        }
                    });
                    viewer.setVisible(true);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "Chyba při otevírání souboru: " + e.getMessage(), "Chyba", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }

    /**
     * Open the selected file in the internal editor (editable)
     */
    private void editSelectedFile() {
        int sel = resultsTable.getSelectedRow();
        if (sel >= 0) {
            FileItem item = tableModel.getResult(sel);
            if (item != null && !item.isDirectory() && !"..".equals(item.getName())) {
                try {
                    Frame owner = (Frame) SwingUtilities.getWindowAncestor(this);
                    FileEditor editor = new FileEditor(owner, item.getFile(), config, false);
                    editor.addWindowListener(new java.awt.event.WindowAdapter() {
                        @Override
                        public void windowClosed(java.awt.event.WindowEvent e) {
                            resultsTable.requestFocusInWindow();
                        }
                    });
                    editor.setVisible(true);
                } catch (Exception e) {
                    JOptionPane.showMessageDialog(this, "Chyba při otevírání souboru: " + e.getMessage(), "Chyba", JOptionPane.ERROR_MESSAGE);
                }
            }
        }
    }
    
    /**
     * Model tabulky pro výsledky hledání
     */
    private class ResultsTableModel extends AbstractTableModel {
        
        private final String[] columnNames = {"Cesta", "Velikost", "Datum změny"};
        private List<FileItem> results = new ArrayList<>();
        
        public void addResult(FileItem item) {
            results.add(item);
            fireTableRowsInserted(results.size() - 1, results.size() - 1);
        }
        
        public void clear() {
            results.clear();
            fireTableDataChanged();
        }
        
        public FileItem getResult(int row) {
            return results.get(row);
        }
        
        @Override
        public int getRowCount() {
            return results.size();
        }
        
        @Override
        public int getColumnCount() {
            return columnNames.length;
        }
        
        @Override
        public String getColumnName(int column) {
            return columnNames[column];
        }
        
        @Override
        public Object getValueAt(int rowIndex, int columnIndex) {
            FileItem item = results.get(rowIndex);
            switch (columnIndex) {
                case 0:
                    return item.getPath();
                case 1:
                    return item.getFormattedSize();
                case 2:
                    return item.getFormattedDate();
                default:
                    return null;
            }
        }
    }
}
