package tmcsim.client.cadclientgui.screens;

import java.awt.BorderLayout;
import java.awt.Color;
import static java.awt.Component.LEFT_ALIGNMENT;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;

/**
 * This class contains the view and controller for the Login screen. The view
 * was not built using a GUI builder plug-in (but may want to consider doing so
 * in the future), and the controller uses listeners to control how the view and
 * data act.
 *
 * @author Vincent
 */
public class Login extends JFrame
{
    private Box login;
    private JComboBox<String> userNameCombo;
    private JTextField passwordField;
    public static String kNamePrompt = "Enter your name";
    /** a list of student names that will be displayed on the login screen */
    private Vector<String> students;
    
    public Login(String studentNamesFile)
    {
        readNamesFile(studentNamesFile);
        initView();
    }

    /** 
     * A list of student names is read from a file.  The intent is to allow the
     * system operators to customize the login display for each training session
     * with the names of participants in that training. 
     * @param studentNamesFile the full path to a text file of student names
     * @author jdalbey  ticket #206
     */
    private void readNamesFile(String studentNamesFile)
    {
        FileInputStream fis = null;
        try {
            // Prepare an input stream from the names file
            fis = new FileInputStream(studentNamesFile);
            // Scan the names into a string
            Scanner s = new Scanner(fis).useDelimiter("\\A");
            String out = s.next();
            // split string into an array
            String[] results = out.split("\\n");
            // Initialize the student name list
            students = new Vector();
            // Make sure to truncate names before putting in list
            for (String name: results)
            {
                String truncName = name.trim();
                // Limit name length so it fits in the combo box
                if (truncName.length() > 26)
                {
                    truncName = truncName.substring(0,25);
                }
                // Add the validated name to the list of students
                students.add(truncName);
            }
            // Append the default name 
            students.add("Anonymous Trainee");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                fis.close();
            } catch (IOException ex) {
                Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    private ActionListener newEnterActionListener()
    {
        return new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                setVisible(false);
                // Extract the selected student name from the combo box
                String userEntry = (String) userNameCombo.getSelectedItem();
                ScreenManager.setUserName(userEntry);
                ScreenManager.openCADMenu();
                ScreenManager.openAssignedIncidents();
                ScreenManager.openUnitStatus();
                ScreenManager.openPendingIncidents();
                ScreenManager.openPowerlineUI();
                // a secret password allows special permission
                if (!passwordField.getText().equals("Dispatcher"))
                {
                    ScreenManager.setDispatcherAuthority(false);
                }
            }
        };
    }

    private ActionListener newExitActionListener()
    {
        return new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                System.exit(0);
            }
        };
    }

    private void initView()
    {
        // create a combo box containing the student names
        userNameCombo = new JComboBox<String>(students);
        // Create a scrollbar after ten names
        userNameCombo.setMaximumRowCount(10);
        userNameCombo.setForeground(Color.BLUE);
        userNameCombo.setFont(new Font("Arial", Font.BOLD, 14));
        
        login = new Box(BoxLayout.Y_AXIS);
        login.setAlignmentX(LEFT_ALIGNMENT);
        JPanel whiteBackground = new JPanel();
        whiteBackground.setLayout(new BorderLayout());
        whiteBackground.setAlignmentX(LEFT_ALIGNMENT);
        whiteBackground.setBackground(Color.WHITE);
        whiteBackground.setMaximumSize(new Dimension(750, 150));
        whiteBackground.setMinimumSize(new Dimension(750, 150));
        whiteBackground.setPreferredSize(new Dimension(750, 150));
        // Add TriTech banner to top of screen (ticket #205)
        try {
            BufferedImage myPicture = ImageIO.read(new File("images/TritechLoginBanner.png"));
            JLabel picLabel = new JLabel(new ImageIcon(myPicture));
            whiteBackground.add(picLabel, BorderLayout.CENTER);
        } catch (IOException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
        }
        login.add(whiteBackground);

        JPanel blueBackground = new JPanel();
        blueBackground.setAlignmentX(LEFT_ALIGNMENT);
        blueBackground.setBackground(new Color(50, 150, 200));
        blueBackground.setMaximumSize(new Dimension(750, 350));
        blueBackground.setMinimumSize(new Dimension(750, 350));
        blueBackground.setPreferredSize(new Dimension(750, 350));

        JLabel title = new JLabel();
        // Check if we are running from a jar to put message from manifest into title
        Package clientpkg = Login.class.getPackage();
        String builddate = clientpkg.getImplementationVersion();
        String version = "";
        if (builddate != null)
        {
            version = "          (build " + builddate + ")";
        }
        else // We're running from a dev environment
        {
            version = "           00-00-00 00:00";
        }

        title.setText("Inform CAD 5.3 Patch 5 ");
        title.setHorizontalAlignment(SwingConstants.CENTER);
        title.setFont(new Font("Arial", Font.PLAIN, 22));
        title.setForeground(Color.WHITE);
        title.setMaximumSize(new Dimension(750, 100));
        title.setMinimumSize(new Dimension(750, 100));
        title.setPreferredSize(new Dimension(750, 100));
        blueBackground.add(title);

        JLabel builddateLabel = new JLabel(version);
        builddateLabel.setForeground(Color.WHITE);
        builddateLabel.setHorizontalAlignment(SwingConstants.CENTER);
        blueBackground.add(builddateLabel);

        Box leftBox = new Box(BoxLayout.Y_AXIS);
        leftBox.setMaximumSize(new Dimension(350, 90));
        leftBox.setMinimumSize(new Dimension(350, 90));
        leftBox.setPreferredSize(new Dimension(350, 90));
        leftBox.setAlignmentX(LEFT_ALIGNMENT);

        JLabel userNameLabel = new JLabel("User name ");
        userNameLabel.setForeground(Color.WHITE);
        Box userNameBox = new Box(BoxLayout.X_AXIS);
        userNameBox.setAlignmentX(LEFT_ALIGNMENT);
        userNameBox.add(Box.createHorizontalStrut(10));
        userNameBox.add(userNameLabel);
        userNameBox.add(userNameCombo);
        leftBox.add(userNameBox);

        JLabel passwordLabel = new JLabel("Password  ");
        passwordLabel.setForeground(Color.WHITE);
        passwordField = new JTextField("Not required");
        passwordField.setEnabled(false);
        Box passwordBox = new Box(BoxLayout.X_AXIS);
        passwordBox.setAlignmentX(LEFT_ALIGNMENT);
        passwordBox.add(Box.createHorizontalStrut(10));
        passwordBox.add(passwordLabel);
        passwordBox.add(passwordField);
        leftBox.add(Box.createVerticalStrut(10));
        leftBox.add(passwordBox);

        JButton enter = new JButton("Login");
        enter.addActionListener(newEnterActionListener());
        JButton newPassword = new JButton("New Password");
        newPassword.setEnabled(false);
        JButton exit = new JButton("Exit");
        exit.addActionListener(newExitActionListener());
        JButton selectAll = new JButton("Select All");
        selectAll.setEnabled(false);
        JButton unselectAll = new JButton("Unselect all");
        unselectAll.setEnabled(false);
        Box buttonBox = new Box(BoxLayout.X_AXIS);
        buttonBox.setAlignmentX(LEFT_ALIGNMENT);
        buttonBox.add(Box.createHorizontalStrut(75));
        buttonBox.add(enter);
        buttonBox.add(Box.createHorizontalStrut(20));
        buttonBox.add(newPassword);
        buttonBox.add(Box.createHorizontalStrut(20));
        buttonBox.add(exit);
        buttonBox.add(Box.createHorizontalStrut(125));
        buttonBox.add(selectAll);
        buttonBox.add(Box.createHorizontalStrut(10));
        buttonBox.add(unselectAll);

        Box rightBox = new Box(BoxLayout.Y_AXIS);
        rightBox.setAlignmentX(LEFT_ALIGNMENT);
        rightBox.setMaximumSize(new Dimension(250, 90));
        rightBox.setMinimumSize(new Dimension(250, 90));
        rightBox.setPreferredSize(new Dimension(250, 90));
        JLabel position = new JLabel("Positions:");
        position.setPreferredSize(new Dimension(250, 20));
        position.setMaximumSize(new Dimension(250, 20));
        position.setMinimumSize(new Dimension(250, 20));
        position.setBackground(Color.BLACK);
        position.setHorizontalAlignment(SwingConstants.LEFT);
        position.setForeground(Color.WHITE);
        rightBox.add(position);
        JPanel list = new JPanel();
        rightBox.add(list);

        Box centerBox = new Box(BoxLayout.X_AXIS);
        centerBox.setAlignmentX(LEFT_ALIGNMENT);
        centerBox.add(leftBox);
        centerBox.add(Box.createHorizontalStrut(75));
        centerBox.add(rightBox);
        blueBackground.add(centerBox);
        blueBackground.add(Box.createVerticalStrut(125));
        blueBackground.add(buttonBox);
        login.add(blueBackground);

        getContentPane().add(login);
        setUndecorated(true);
        pack();
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }
    
    /** Local main for unit testing */
    public static void main(String[] args) 
    {
        new Login("config/student_names.txt");
    }
    
}