package com.itant.filetransfer;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

/**
 * 文件发送者，也是服务器端(创建热点，监听有人连上之后并且勾选了一个或一个以上的应用发送按钮才可点击)
 * @author 詹子聪
 *
 */
public class SenderActivity extends Activity implements OnClickListener {

	private Button btn_send;
	private TextView tv_apks;
	
	private WifiManager mWifiManager;
	
	private static final int CLIENT_DISCONNECTED = 0;
	private static final int CLIENT_CONNECTED = 1;
	private static final int HOT_SPOT_READY = 2;
	private ServerSocket mServerSocket;
	private Socket mClient;
	private boolean mIsServiceDestoryed = false;
	/**往客户端发送文件的入口**/
	private DataOutputStream mOutputStream;
	
	private List<String> mApkList;
	
	private Handler mServerHandler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case CLIENT_DISCONNECTED:
				btn_send.setEnabled(false);
				break;
			case CLIENT_CONNECTED:
				// 客户端连上了(监听断开)
				btn_send.setEnabled(true);
				break;
			case HOT_SPOT_READY:
				// 热点创建成功，开启socket服务器端，监听客户端连接(监听断开)
				new ServerThread().start();
				break;

			default:
				break;
			}
			return true;
		}
	});
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sender);
		
		btn_send = (Button) findViewById(R.id.btn_send);
		btn_send.setOnClickListener(this);
		tv_apks = (TextView) findViewById(R.id.tv_apks);
		
		mApkList = new ArrayList<String>();
		new GetApksTask().execute();
		
		mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
		// 创建热点
		String hotSpotName = "backup" + System.currentTimeMillis();
		createAP(hotSpotName, "12345678");
	}
	
	private class GetApksTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			PackageManager pm = getPackageManager();
			StringBuilder sb = new StringBuilder();
			List<ApplicationInfo> applicationInfos = pm.getInstalledApplications(PackageManager.GET_META_DATA);
			for (ApplicationInfo applicationInfo : applicationInfos) {
				
				if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
					// 非系统应用
					mApkList.add(applicationInfo.publicSourceDir);
				}
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			
			StringBuilder builder = new StringBuilder();
			for (String dir : mApkList) {
				builder.append(dir).append("\n");
			}
			
			tv_apks.setText(builder.toString());
		}
	}
	
	/**
     * 创建热点
     * @param ssid 热点名称
     * @param password 密码
     */
    private void createAP(String ssid, String password){
		if (mWifiManager.isWifiEnabled()) {
			// 如果开启了WIFI，则将它关闭
			mWifiManager.setWifiEnabled(false);
		} 
		
		
		try{
			WifiConfiguration wifiConfiguration = new WifiConfiguration();
			//热点名称
			wifiConfiguration.SSID = ssid;
			//热点密码
			wifiConfiguration.preSharedKey = password;
			wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
			wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
			wifiConfiguration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
			wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
			wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
			wifiConfiguration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
			wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
			wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);

			// 利用反射获取开启热点的方法创建热点
			NetworkTools.setWifiApEnabled(mWifiManager, wifiConfiguration, true);
			
			final Method isHotSpotEnable = mWifiManager.getClass().getMethod("isWifiApEnabled");
			
			// 每隔1.5秒查看热点是否创建成功
			new Thread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					while (true) {
						try {
							boolean hotSpotEnable = (boolean) isHotSpotEnable.invoke(mWifiManager);
							if (hotSpotEnable) {
								mServerHandler.sendEmptyMessage(HOT_SPOT_READY);
								break;
							}
							Thread.sleep(1500);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}).start();
		}catch(Exception e){
			e.printStackTrace();
		}
    }
    
    /**
     * 服务器端
     * @author 詹子聪
     *
     */
    private class ServerThread extends Thread {
    	
		@Override
    	public void run() {
            try {
                mServerSocket = new ServerSocket(8688);
            } catch (IOException e) {
                System.err.println("establish tcp server failed, port:8688");
                e.printStackTrace();
                return;
            }

            while (!mIsServiceDestoryed) {
                try {
                    // 一个客户端连接上了
                    mClient = mServerSocket.accept();
                    mOutputStream = new DataOutputStream(mClient.getOutputStream());
                    mServerHandler.sendEmptyMessage(CLIENT_CONNECTED);
                } catch (IOException e) {
                    e.printStackTrace();
                    // 如果客户端断开连接，这里会不会执行？？？？？？？？？？？？？？？？？？？？
                    mServerHandler.sendEmptyMessage(CLIENT_DISCONNECTED);
                }
            }
    	}
    }
    
    @Override
    protected void onDestroy() {
    	// TODO Auto-generated method stub
    	super.onDestroy();
    	mIsServiceDestoryed = false;
    	
    	// 关闭流
    	if (mServerSocket != null) {
    		try {
    			if (mOutputStream != null) {
    				mOutputStream.close();
    			}
    			if (mClient != null) {
    				mClient.close();
    			}
    			mServerSocket.close();
    		} catch (IOException e) {
    			e.printStackTrace();
    		}
    	}
    }

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_send:
			int i = 0;
			for (String dir : mApkList) {
				
				
				final File file = new File(dir);
				
				try {
					// 把文件名告诉客户端
					mOutputStream.writeUTF("a"+i+".apk");  
					mOutputStream.flush();
					
					// 把文件长度诉客户端，否则不知道一个文件结尾在哪
					mOutputStream.writeLong(file.length());  
					mOutputStream.flush();
					
					DataInputStream inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
					byte buf[] = new byte[1024];
			        int len = -1;
		        
		            while ((len = inputStream.read(buf)) != -1) {
		            	mOutputStream.write(buf, 0, len);
		            }
		            mOutputStream.flush();
		            inputStream.close();
		            // 一个文件结束了
				} catch (IOException e1) {
					e1.printStackTrace();
				}  
				
				
				i++;
				if (i > 3) {
					break;
				}
			}
			
			
			
			
				
			break;

		default:
			break;
		}
	}
}
