import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import java.text.SimpleDateFormat;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.proxy.ProxyInfo;
import org.jivesoftware.smack.proxy.ProxyInfo.ProxyType;
import org.jivesoftware.smack.PacketListener;
import org.jivesoftware.smack.filter.MessageTypeFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.util.StringUtils;


public class location_1 
{
    private String username;
    private String password;
	private String inipath = "";
    private String[] ToAddress;

    private Timer timer = new Timer();
    
    //接続先の設定情報
    private String SERVER_ADDRSS = "penta-02.ptgw.net";
    private String SERVICE_NAME = "pneta-02.ptgw.net";
    private int SERVER_PORT = 5222;

    private ConnectionConfiguration connectionConfiguration ;
    private XMPPConnection xmppConnection;

	private PacketFilter filter = new MessageTypeFilter(Message.Type.chat);	
    private int tct = 0;
	private SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");


    public static void main( String[] args )
    {
        location_1 main = new location_1(args);
    }
        
    public location_1( String[] args )
    {
		if( args.length < 2)
		{
			System.out.println("usage : java XmppTest [UserAddress] [Password]");
		}

        username = args[0];
        password = args[1];
//		inipath  = args[2];

		//■送信先ユーザーをCSVから読み込む
/*
	    try
	    {
	     	File csv = new File(inipath); // CSVデータファイル

	      	BufferedReader br = new BufferedReader(new FileReader(csv));
			String line = "";
			
			if((line = br.readLine()) != null)
			{
				ToAddress = line.split("\\,");
	      	}
	      	tct = ToAddress.length;
	    }
	    catch (FileNotFoundException e)
		{
	      // Fileオブジェクト生成時の例外捕捉
	      e.printStackTrace();
		}catch (IOException e) {
	      // BufferedReaderオブジェクトのクローズ時の例外捕捉
	      e.printStackTrace();
	    }
*/
        //■XMPP接続(ログイン)
        try
        {
			connect();
        }
        catch (XMPPException e)
        {
            System.out.print("connection failed. message="+e.getMessage());
            return;
        }

        //■送信先へのセッション作成
        try
        {
           	//セッション作成
            sendMessage(); 
        }
        catch (XMPPException e)
        {
            System.out.print("Failed to send message. message="+e.getMessage());
            return;
        }
        catch (IOException e)
        {
            System.out.print("IOException occured. message="+e.getMessage());
            return;
        }
    }
        
    /*■■XMPP接続
     * 接続する。
     * @throws XMPPException
     */
    private void connect() throws XMPPException
    {
		//接続情報の設定
        connectionConfiguration = new ConnectionConfiguration(SERVER_ADDRSS, SERVER_PORT,SERVICE_NAME);
		
		//XMPP接続準備
        xmppConnection = new XMPPConnection(connectionConfiguration);
        
		//XMPP接続
        xmppConnection.connect();
        
        //ログイン
        xmppConnection.login(username, password);
    }
        
    /*■■XMPP受信
     * メッセージの受信
     * @throws XMPPException
     * @throws IOException 
     */
    public void sendMessage() throws XMPPException, IOException
    {
    	
    	
    	
	  			new Thread(new Runnable()
	  			{
	  				@Override
	  				public void run()
	  				{
	  			    	xmppConnection.addPacketListener(_MyPacketListener, filter);
	  				}
  				}).start();
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	
    	/*
		final String UserName = User;
        final Chat chat = xmppConnection.getChatManager().createChat(Address, new MessageListener() {
            @Override
            //メッセージ受信処理
            public void processMessage(Chat chat, Message message ) 
            {
				//System.out.println(message.getFrom()+":"+message.getBody());
				//if(message.getBody() == null)
				System.out.println(UserName + message.getBody());

                //受信結果をログに出力
                try
                {
                	File file = new File("/var/www/html/ansys/qgis/xmpp/log/_location.txt");
                	
					//System.out.println("/var/www/html/ansys/qgis/xmpp/log/" + UserName + "_location.txt");
                	
                	if (!checkBeforeWritefile(file))
                	{
						try
						{

						    file.createNewFile();
						    file.setWritable(true, false);
						}
						catch(IOException e)
						{
						    System.out.println(e);
						}
                	}

	                //File file = new File("/var/www/html/ansys/qgis/xmpp/log/location.txt");
	                	
					if (checkBeforeWritefile(file))
					{
						PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
						
						Calendar now = Calendar.getInstance(); //インスタンス化
    					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
						pw.println(sdf.format(now.getTime()) + "," + UserName + "," + message.getBody());
    		        	pw.close();
    		        }
  				}
				catch(IOException e)
  				{
  					System.out.println(e);
				}
			}
        });
            
		System.out.println("Success!");
		
		*/
    }

	private PacketListener _MyPacketListener = new PacketListener()
	{
		@Override
		public void processPacket(Packet packet)
		{
			Message message = (Message) packet;
			
			//Log.d(CommonUtility.TAG, "[XMPP.Recieve]start");
  	        
  	        //■受信メッセージのＮｕｌｌ判定
  	        if (message.getBody() != null)
  	        {
  	            String msgBody = message.getBody();
  	            String msgFrom = message.getFrom();
  	            
				String[] sp = msgFrom.split("@");

                //受信結果をログに出力
                try
                {
					Calendar now = Calendar.getInstance(); //インスタンス化
                	String FileName = sdf2.format(now.getTime());
                	File file = new File("/www/ansys/xmpp/log/receive_" + FileName + ".log");
                	
                	if (!checkBeforeWritefile(file))
                	{
						try
						{
						    file.createNewFile();
						    file.setWritable(true, false);
						}
						catch(IOException e)
						{
						    System.out.println(e);
						}
                	}

					if (checkBeforeWritefile(file))
					{
						PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file,true)));
    					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
						pw.println(sdf.format(now.getTime()) + "," + message.getBody());
    		        	pw.close();
    		        }
  				}
				catch(IOException e)
  				{
  					System.out.println(e);
				}
  	        	System.out.println(sp[0] + "," + msgBody);
  	        }
		}
	};
        

	//■■ファイル有無をチェック
	private static boolean checkBeforeWritefile(File file)
	{
		if(file.exists())
		{
			if (file.isFile() && file.canWrite())
			{
				return true;
			}
		}
	    return false;
	}

}
