package com.example.client;

import android.R.string;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Timer;
import java.util.TimerTask;

public class NetWork {
    
    private String TAG = NetWork.class.getSimpleName();
    
    // 单例
    private static NetWork _instance = null;
    
    private NetWork() {}
    
    public static NetWork getInstance() {
        if (null == _instance) {
            _instance = new NetWork();
        }
        
        return _instance;
    }

    private final String IP_ADDR = "192.168.0.5:60006";

    private boolean isConnecting = false;
    private boolean isFirstConnecting = false;
    
    private Thread mThreadClient = null;
    private Socket mSocketClient = null;
    static BufferedReader mBufferedReaderServer = null;
    static PrintWriter mPrintWriterServer = null;
    static BufferedReader mBufferedReaderClient = null;
    static PrintStream mPrintWriterClient = null;
    
    private  String recvMessageClient = "";
    private  String recvMessageServer = "";
    
    private Timer mTimerNetwork; 
    private Timer mTimerCheckConnect;
    
    public void start()
    {
        
        if (!isConnecting)
        {
            StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()        
            .detectDiskReads()        
            .detectDiskWrites()        
            .detectNetwork()   // or .detectAll() for all detectable problems       
            .penaltyLog()        
            .build());        
            StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()        
            .detectLeakedSqlLiteObjects()     
            .penaltyLog()        
            .penaltyDeath()        
            .build()); 

            if (mTimerNetwork == null)
            {
                // 每3s向PC发送一次生理指标
                mTimerNetwork = new Timer();
                mTimerNetwork.schedule(new TimerTask(){
                    @Override
                    public void run() {
                        mHandler.post(mRunnableNetwork);
                    }
                }, 3000, 3000);
            }
            
            if (mTimerCheckConnect == null)
            {
                // 每s重新检查连接
                mTimerCheckConnect = new Timer();
                mTimerCheckConnect.schedule(new TimerTask(){
                    @Override
                    public void run() {
                        mHandler.post(mRunnableCheckConnect);
                    }
                }, 1000, 1000);
            }

            // 尝试连接服务器           
            Log.i(TAG, "尝试连接服务器  ");
                
            if (mThreadClient == null)
            {
                mThreadClient = new Thread(mRunnable);
                mThreadClient.start();   
            }
        }
    }
      

    public void stop()
    {
        if (isConnecting) 
        {               
        	mTimerCheckConnect.cancel();
        	mTimerNetwork.cancel();
            NetWork.this.interruptNetwork("停止连接");
        }
    }
    
    
    Handler mHandler = new Handler()
    {                                       
          public void handleMessage(Message msg)                                        
          {                                         
              super.handleMessage(msg);         
              if(msg.what == 0)
              {
                  Log.i(TAG, "Server: "+ recvMessageServer);
              }
              else if(msg.what == 1)
              {
                  Log.i(TAG, "Client: "+ recvMessageClient);
              }
          }                                 
     };
     
     
     // 每秒检查网络连接
     private Runnable mRunnableCheckConnect = new Runnable() 
     {
         public void run()
         {
             if (!isConnecting && isFirstConnecting)
             {   
                 // 尝试连接服务器           
                 Log.i(TAG, "尝试连接服务器  ");
                     
                 isFirstConnecting = false;

                 mThreadClient = new Thread(mRunnable);
                 mThreadClient.start();   
             }
         }
     };
     
     
     // 线程:监听服务器发来的消息
     private Runnable mRunnable = new Runnable() 
     {
         @Override
         public void run()
         {   
             String msgText = IP_ADDR;
             if(msgText.length() <= 0)
             {
                 recvMessageClient = "IP不能为空！\n";//消息换行
                 Message msg = new Message();
                 msg.what = 1;
                 mHandler.sendMessage(msg);
                 return;
             }
             
             int start = msgText.indexOf(":");
             if( (start == -1) || (start+1 >= msgText.length()) )
             {
                 recvMessageClient = "IP地址不合法\n";//消息换行
                 Message msg = new Message();
                 msg.what = 1;
                 mHandler.sendMessage(msg);
                 return;
             }

             String sIP = msgText.substring(0, start);
             String sPort = msgText.substring(start+1);
             int port = Integer.parseInt(sPort);             
             
             Log.d("gjz", "IP:"+ sIP + ":" + port);      

             if (!isConnecting)
             {
                 try 
                 {               
                     //连接服务器
                     mSocketClient = new Socket(sIP, port);  //portnum
                     //取得输入、输出流
                     mBufferedReaderClient = new BufferedReader(new InputStreamReader(mSocketClient.getInputStream()));
                     
                     mPrintWriterClient = new PrintStream(mSocketClient.getOutputStream(), true);
                     
                     // 已经连接
                     isConnecting = true;
                     isFirstConnecting = true;

                     recvMessageClient = "已经连接server!\n";//消息换行
                     Message msg = new Message();
                     msg.what = 1;
                     mHandler.sendMessage(msg);      
                     //break;
                 }
                 catch (Exception e) 
                 {
                     recvMessageClient = "连接IP异常:" + e.toString() + e.getMessage() + "\n";//消息换行
                     
                     NetWork.this.interruptNetwork("连接异常:中断线程");
                     
                     Message msg = new Message();
                     msg.what = 1;
                     mHandler.sendMessage(msg);
                     return;
                 }           

             }
         }
     };
     
     
    private synchronized void interruptNetwork(String str)
    {
    	// 中断线程
        isConnecting = false;
        isFirstConnecting = true;

        Log.i(TAG, str); 
        
        mThreadClient.interrupt();
    }
     

    boolean isSendUnlogin = false;
    private Runnable mRunnableNetwork = new Runnable() {
        @Override
        public void run() {
            mHandler.sendEmptyMessage(1);

            if (isConnecting)
            {               

            }

        }
    };
    
    private void sendtoServer(String msg)
    {
        // 发送给PC服务器
        if ( isConnecting && mSocketClient != null ) 
        {
            if(msg.length() <= 0)
            {
                Log.i(TAG, "发送内容不能为空!");
            }
            else
            {
                try 
                {                
                    // 发送给服务器
                    mPrintWriterClient.print(msg);
                    mPrintWriterClient.flush();
                }
                catch (Exception e) 
                {
                    // TODO: handle exception
                    Log.i(TAG, "发送异常：" + e.getMessage());
                }
            }
        } 
    }
}
