/*
 * Created on 09.03.2010.
 *
 */
package main;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.TitledBorder;

public class Client {

    static  JFrame frame = new JFrame();
    static JTextArea text = new JTextArea();
    
    static JButton send = new JButton("SEND TEXT"),reset = new JButton("RESET TEXT");    
    static JButton sendXml = new JButton("SEND XML");
    
    static JButton zReport = new JButton("Z report"),xReport = new JButton("X report"),dayStarted= new JButton("fisc.day started");
    static JButton readVats = new JButton("read vats"),readJournal = new JButton("read journal");
    static JButton stateZ = new JButton("read Z state"),stateBill = new JButton("read Bill state");
    static JButton PLUall = new JButton("read all PLU"),PLUsold = new JButton("read sold PLU");


    private static byte[] buffer = new byte[1024*1024];
    
    static{
        JPanel pp = new JPanel(new BorderLayout(10,10));
        pp.setBorder(new TitledBorder("testing panel"));
        pp.setPreferredSize(new Dimension(800,600));
        frame.setContentPane(pp);
        text.setLineWrap(true);
        pp.add(new JScrollPane(text),BorderLayout.CENTER);
        frame.pack();
        
        JPanel bp = new  JPanel(new GridLayout(15,1,5,5));
        bp.add(send);
        bp.add(reset);
        bp.add(new JLabel());
        bp.add(sendXml);
        JPanel ert = new JPanel(new BorderLayout());
        ert.add(bp,BorderLayout.NORTH);
        ert.add(new JPanel(),BorderLayout.CENTER);
        pp.add(ert,BorderLayout.WEST);
        
        JPanel commPanel = new JPanel(new GridLayout(15,1,5,5));
        commPanel.add(zReport);
        commPanel.add(xReport);
        commPanel.add(new JLabel());
        commPanel.add(dayStarted);
        commPanel.add(new JLabel());
        commPanel.add(readVats);
        commPanel.add(readJournal);
        commPanel.add(new JLabel());
        commPanel.add(stateZ);
        commPanel.add(stateBill);
        commPanel.add(new JLabel());
        commPanel.add(PLUall);
        commPanel.add(PLUsold);
        JPanel ppp = new JPanel(new BorderLayout());
        ppp.setBorder(new TitledBorder("commands"));
        ppp.add(commPanel,BorderLayout.NORTH);
        ppp.add(new JPanel(),BorderLayout.CENTER);
        pp.add(ppp,BorderLayout.EAST);

        frame.setTitle("RS CLIENT");
        frame.setLocationRelativeTo(null);
        frame.setAlwaysOnTop(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

    public static void main(String[] arg) {
        send.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                new Thread() {
                    public void run() {
                        new Client(3535,"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><NEFISKALNI_TEKST><DATA TXT=\"" +
                                text.getText() +
                        "\"/></NEFISKALNI_TEKST>");
                    }
                }.start();  
            }
        });
        reset.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
              text.setText("");  
            }
        });
        

        sendXml.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {

                final String readString;
                try {
                    JFileChooser fc = new JFileChooser();
                    fc = new JFileChooser(".");
                    fc.setAcceptAllFileFilterUsed(true);
                    int retVal = fc.showOpenDialog(frame);
                    if (retVal != JFileChooser.APPROVE_OPTION)return;
                    File f = fc.getSelectedFile();
                    if(f==null)return;

                    String str = "",in;
                    BufferedReader br = new BufferedReader(new FileReader(f));
                    try {
                        while((in = br.readLine())!=null)str+=in;
                    } finally {
                        br.close();
                    }
                    readString = str;
                    
                } catch (Exception e1) {
                    Client.text.append("Exception reading file: " + e1);
                    Client.text.append("\r\n");
                    return;
                }
                
                new Thread() {
                    public void run() {
                        new Client(3535,readString);
                    }
                }.start();
                
            }
        });

        zReport.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("DNEVNI_IZVESTAJ");
            }
        });
        xReport.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("PRESEK_STANJA");
            }
        });
        dayStarted.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("PROVERI_FISKALNI_DAN");
            }
        });
        readVats.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                readVats();
            }
        });
        readJournal.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("ZURNAL");
            }
        });
        stateZ.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("STANJE_KASE");
            }
        });
        stateBill.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("STANJE_RACUNA");
            }
        });
        PLUall.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("ARTIKLI");
            }
        });
        PLUsold.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                sendCommand("PRODATI_ARTIKLI");
            }
        });
        
        frame.setVisible(true);
    }
    
    protected static void readVats() {
        new Thread() {
            public void run() {
                new Client(3535,"<?xml version='1.0' encoding='UTF-8' standalone='yes'?><KOMANDE><DATA CMD='USER_COMMAND' COMMAND_BYTE='32'> </DATA></KOMANDE>");
            }
        }.start();  
    }

    private static void sendCommand(final String cmd){
        new Thread() {
            public void run() {
                new Client(3535,"<?xml version='1.0' encoding='UTF-8' standalone='yes'?><KOMANDE><DATA CMD='" +
                		cmd +
                		"'/></KOMANDE>");
            }
        }.start();  
    }

    InputStream Sinput;       // to read the socker
    OutputStream Soutput; // towrite on the socket
    Socket socket;

    // Constructor connection receiving a socket number
    Client(int port,String txt ) {

        text.setText(">>>");
        // we use "localhost" as host name, the server is on the same machine
        // but you can put the "real" server name or IP address
        try {
            socket = new Socket("localhost", port);
        }
        catch(Exception e) {
            Client.text.setText("Error connectiong to server:" + e);
            Client.text.append("\r\n");
            return;
        }
        Client.text.setText("Connection accepted " +
                socket.getInetAddress() + ":" +
                socket.getPort());
        Client.text.append("\r\n");

        /* Creating both Data Stream */
        try
        {
            Soutput = socket.getOutputStream();
            Sinput = socket.getInputStream();
        }
        catch (IOException e) {
            Client.text.append("Exception creating new Input/output Streams: " + e);
            Client.text.append("\r\n");
            return;
        }
        
        // send the string to the server
        Client.text.append("\r\n");
        Client.text.append("SENDING:\"" + txt);
        Client.text.append("\r\n");
        try {
            /*******************SENDING*****************/
            Soutput.write(txt.getBytes());
            Soutput.flush();
            socket.shutdownOutput();
            /*******************SENDING*****************/
        }
        catch(IOException e) {
            Client.text.append("Error writting to the socket: " + e);
            Client.text.append("\r\n");
            return;
        }
        
        

        /* Creating both Data Stream */
        try
        {
            

            /*******************READING*****************/
            int pos=0,t=0;
            long time= System.currentTimeMillis();
            while((t = Sinput.read(buffer,pos,buffer.length-pos))>=0){
                pos+=t;
                if(System.currentTimeMillis()-time>60000)throw new Exception("TIMEOUT!");
            }
            
            String reply = new String(buffer,0,pos);
            /*******************READING*****************/

            Client.text.append("\r\n");
            Client.text.append("RECEIVED: " + reply);
            Client.text.append("\r\n");
            
        } catch (Exception e) {
            Client.text.append("Exception reading error: " + e);
            Client.text.append("\r\n");
            return;
        }
        
    }  
    
}
