package BWP.MobileSale;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.forks.jsonrpc.RpcFacade;

import BWP.MobileSale.Util.ConfigUtil;
import BWP.MobileSale.Util.DialogUtil;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ClientUpdateActivity extends Activity{
	final String tag = "ClientUpdateActivity";

	private int fileSize;
	private int downLoadFileSize;

	private ProgressBar progressBar;
	private TextView textViewProgress;
	String fullpathfilename;
	private Button installButton;
	boolean secceed=true;
	private class DownLoadTask extends AsyncTask<Void, Integer, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			try {
				
				down_file();
			} catch (Exception ex) {
				secceed=false;
				Log.d(tag, "错误"+ex.getMessage());				
				System.out.println("错误"+ex.getMessage());
				this.cancel(true);
			}
			return null;
		}

		public void down_file() throws Exception {

			String serverUri = ConfigUtil
					.getServerUri(ClientUpdateActivity.this);
			Log.i(tag, String.format("get server uri:%s", serverUri));

			String method = "/Sale/Sale/Rpcs/MobileSaleClientRpc/GetAndroidClientUrl";
			
			String url = RpcFacade.rpcCall(method);
			int subStrStart = url.indexOf("/", 1);
			if (serverUri.endsWith("/")) {
				subStrStart++;
			}
			url = serverUri + url.substring(subStrStart);
			Log.d(tag, "start download " + url);

			String saveFolder = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			fullpathfilename = saveFolder + File.separator + "MobileSale.apk";

			Log.d("MobileSale", String.format("save %s to %s", url, fullpathfilename));
			
			URL myURL = new URL(url);
			URLConnection conn = myURL.openConnection();
			conn.connect();
			InputStream inputStream = conn.getInputStream();
			fileSize = conn.getContentLength();// 根据响应获取文件大小
			if (fileSize <= 0)
				throw new Exception("无法获知文件大小 ");
			if (inputStream == null)
				throw new Exception("stream is null");
			publishProgress(fileSize);
			FileOutputStream outputStream = new FileOutputStream(fullpathfilename);
			// 把数据存入路径+文件名
			byte buf[] = new byte[1024];
			downLoadFileSize = 0;
			do {
				// 循环读取
				int numread = inputStream.read(buf);
				if (numread == -1) {
					break;
				}
				outputStream.write(buf, 0, numread);
				downLoadFileSize += numread;

				publishProgress();
			} while (true);
			inputStream.close();
		}

		@Override
		protected void onProgressUpdate(Integer... values) {

			if (values.length > 0) {
				progressBar.setMax(values[0]);
			} else {
				progressBar.setProgress(downLoadFileSize);
				int result = downLoadFileSize * 100 / fileSize;
				textViewProgress.setText(result + "%");
			}
			super.onProgressUpdate(values);
		}

		@Override
		protected void onPostExecute(Void result) {

			if(secceed)
			{
				Toast.makeText(ClientUpdateActivity.this, "文件下载完成", 1).show();
				deleteSaleOrderApk();
				installButton.setVisibility(View.VISIBLE);
			}
			else
			{
				Toast.makeText(ClientUpdateActivity.this, "文件下载错误", 1).show();
			}
			
			super.onPostExecute(result);
		}

		@Override
		protected void onPreExecute() {
			progressBar.setMax(fileSize);
			super.onPreExecute();
		}

	}
	
	private void deleteSaleOrderApk()
	{
		try {			
			
			if(checkApkExist("BWP.Sale"))
			{
				DialogUtil.Confirm(this, "青花瓷手机订单系统已停用，请卸载后安装新版本", "卸载", "取消", new DialogInterface.OnClickListener() {
					
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Uri packageURI = Uri.parse("package:BWP.Sale");  
						
						Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);  
						
						startActivity(uninstallIntent);
					}

					
				});
				
			}
			
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}
	
	public boolean checkApkExist(String packageName) {
        if (packageName == null || "".equals(packageName))
                return false;
        try {
                ApplicationInfo info = getPackageManager().getApplicationInfo(packageName,PackageManager.GET_UNINSTALLED_PACKAGES);
                return true;
        } catch (NameNotFoundException e) {
                return false;
        }
}


	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.client_update);
		
		Button returnButton = (Button)findViewById(R.id.Button_Return);
		returnButton.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				finish();
				
			}
		});
		
		progressBar = (ProgressBar)findViewById(R.id.ProgressBar);
		textViewProgress = (TextView)findViewById(R.id.TextView_Progress);

		installButton =(Button)findViewById(R.id.Button_OK);
		installButton.setVisibility(View.GONE);
		installButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(Intent.ACTION_VIEW);
				intent.setDataAndType(Uri.fromFile(new File(fullpathfilename)),
						"application/vnd.android.package-archive");
				startActivity(intent);
			}

		});

		DownLoadTask downLoadTask = new DownLoadTask();
		downLoadTask.execute();

	}
}
