package com.qiyou.mb.android.upgrade;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;

import org.apache.http.Header;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.qiyou.mb.android.QiYouApplication;
import com.qiyou.mb.android.QiYouConstant;
import com.qiyou.mb.android.R;
import com.qiyou.mb.android.utils.Utils;
import com.qiyou.mb.android.utils.log.QLog;

 

public class UpdateManager {

	public static final String TAG ="com.qiyou.UpdateManager";
	public static final String dTAG ="com.qiyou";
	private static final int DOWNLOAD = 1;
	private static final int DOWNLOAD_FINISH = 2;
	HashMap<String, String> mHashMap;
	private String mSavePath;
	private int progress;
	private boolean cancelUpdate = false;
	private Context mContext;
	private ProgressBar mProgress;
	private Dialog mDownloadDialog;
	private Handler mHandler = new Handler()
	{
		@Override
		public void handleMessage(Message msg)
		{
			switch (msg.what)
			{
			case DOWNLOAD:
				mProgress.setProgress(progress);
				break;
			case DOWNLOAD_FINISH:
				installApk();
				break;
			default:
				break;
			}
		};
	};

	public UpdateManager(Context context)
	{
		this.mContext = context;
//		app =(QiYouApplication)context; 
	}

	/**
	 * 濡拷绁存潪顖欐閺囧瓨鏌�
	 */
	public void checkUpdate()
	{
		  String urlStr =QiYouConstant.VERSION_ADDRESS;
		  checkUpdate(urlStr);
		/*if (isUpdate())
		{
			showNoticeDialog();
		} else
		{
 		   Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
		}*/
	}
	boolean isSilence =false;
	public void checkUpdateSilence()
	{
		isSilence=true;
		checkUpdate();
	}

	
	
	
	
	
	 
	  void checkUpdate(String url){
	  
	   
	    QiYouApplication.requestWeb(url, null, new AsyncHttpResponseHandler(){
	    
//		      String msg = "";
		      
		      public void onFailure(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte, Throwable paramAnonymousThrowable)
		      {
		    	  QLog.getLogger().dLog(dTAG,  TAG + ",版本检查错误  onFailure(int, Header[],byte[], Throwable ) was received");
		    	  if(!isSilence)
		    		  Toast.makeText(mContext, "版本检查出错了", Toast.LENGTH_LONG).show();
		      }
		      
		      public void onSuccess(int paramAnonymousInt, Header[] paramAnonymousArrayOfHeader, byte[] paramAnonymousArrayOfByte)
		      {
		      
		        QLog.getLogger().d(dTAG,  TAG + ", response is  " + new String(paramAnonymousArrayOfByte));
		        if (paramAnonymousArrayOfByte != null) {
		             processTxtOnSuccess(paramAnonymousArrayOfByte);
		        }
		      }
		      });
	    
	    
	    
	  } 
	
	  void processTxtOnSuccess(byte[] paramArrayOfByte) {
	 
		  	boolean isUpdate=false;
			  int versionCode = getVersionCode(mContext); 
			  InputStream inputStream = null;  
			  inputStream =new ByteArrayInputStream(paramArrayOfByte);
 			  ParseXmlService service = new ParseXmlService();
				try
				{
					 
					if(inputStream!=null)
						mHashMap = service.parseXml(inputStream);
					
				} catch (Exception e)
				{
					e.printStackTrace();
				}
				if (null != mHashMap)
				{
					int serviceCode = Integer.valueOf(mHashMap.get("version"));
					// need update or not 
					isUpdate =serviceCode > versionCode;
				}	 
				
				if (isUpdate)
				{
					showNoticeDialog();
				} else
				{
					if(!isSilence)
						Toast.makeText(mContext, R.string.soft_update_no, Toast.LENGTH_LONG).show();
				}
			   
		  
	  }
	
	
	
	
	  /**
		 * 濡拷鐓℃潪顖欐閺勵垰鎯侀張澶嬫纯閺傛壆澧楅張锟�	 * 
		 * @return
		 */
		/*private boolean isUpdate()
		{
			// 閼惧嘲褰囪ぐ鎾冲鏉烆垯娆㈤悧鍫熸拱
			int versionCode = getVersionCode(mContext);
			String urlStr =QiYouConstant.VERSION_ADDRESS;
			// 閹跺ersion.xml閺�儳鍩岀純鎴犵捕娑撳绱濋悞璺烘倵閼惧嘲褰囬弬鍥︽娣団剝浼�
//			InputStream inStream = ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
			// 鐟欙絾鐎絏ML閺傚洣娆㈤妴锟介悽鍙樼艾XML閺傚洣娆㈠В鏃囩窛鐏忓骏绱濋崶鐘愁劃娴ｈ法鏁OM閺傜懓绱℃潻娑滎攽鐟欙絾鐎�
			ParseXmlService service = new ParseXmlService();
			try
			{
				InputStream inStream = getInputStreamFromUrl(urlStr);//ParseXmlService.class.getClassLoader().getResourceAsStream("version.xml");
				if(inStream!=null)
					mHashMap = service.parseXml(inStream);
				
			} catch (Exception e)
			{
				e.printStackTrace();
			}
			if (null != mHashMap)
			{
				int serviceCode = Integer.valueOf(mHashMap.get("version"));
				// 閻楀牊婀伴崚銈嗘焽
				if (serviceCode > versionCode)
				{
					return true;
				}
			}
			return false;
		}
		public InputStream getInputStreamFromUrl(String urlStr)
		        throws MalformedURLException, IOException {
	   
			 URL url;
			 URI uri = null ;
			try {
				url = new URL(urlStr); 
			    uri = new URI(url.getProtocol(), url.getHost(), url.getPath(), url.getQuery(), null);
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (URISyntaxException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if(uri==null)return null;
			
			HttpGet httpRequest ;//= new HttpGet( urlStr);
			 httpRequest = new HttpGet( uri);
			HttpResponse response=app.getHttpClient().execute(httpRequest);
		    InputStream inputStream = null;
			QLog.getLogger().d(dTAG, TAG+" urlStr:" + urlStr);

		    QLog.getLogger().d(dTAG, TAG+"response.getStatusLine().getStatusCode():" +response.getStatusLine().getStatusCode());

			if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
				
				
				inputStream =response.getEntity().getContent();
	 
			}		    
		    return inputStream;
	 
		}
		
		*/
	
	/**
	 * 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣锟�	 * 
	 * @param context
	 * @return
	 */
	public   int getVersionCode(Context context)
	{
		int versionCode = 0;
		try
		{
			// 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣鍑ょ礉鐎电懓绨睞ndroidManifest.xml娑撳獘ndroid:versionCode
			versionCode = context.getPackageManager().getPackageInfo("com.qiyou.mb.android", 0).versionCode;
		} catch (NameNotFoundException e)
		{
			Utils.logStackTrace(e, TAG);
		}
		return versionCode;
	}
	
	/**
	 * 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣锟�	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context)
	{
		String versionName = "";
		try
		{
			// 閼惧嘲褰囨潪顖欐閻楀牊婀伴崣鍑ょ礉鐎电懓绨睞ndroidManifest.xml娑撳獘ndroid:versionCode
			versionName = context.getPackageManager().getPackageInfo("com.qiyou.mb.android", 0).versionName;
		} catch (NameNotFoundException e)
		{
			Utils.logStackTrace(e, TAG);
		}
		return versionName;
	}

	/**
	 * 閺勫墽銇氭潪顖欐閺囧瓨鏌婄�纭呯樈濡楋拷
	 */
	private void showNoticeDialog()
	{
		// 閺嬪嫰锟界�纭呯樈濡楋拷
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_update_title);
		String upgradeDetails=mHashMap.get("details");
		
		builder.setMessage( mContext.getString(R.string.soft_update_info) +upgradeDetails );	
		builder.setPositiveButton(R.string.soft_update_updatebtn, new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			    showDownloadDialog();
			}
		});
		// 缁嬪秴鎮楅弴瀛樻煀
		builder.setNegativeButton(R.string.soft_update_later, new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		});
		Dialog noticeDialog = builder.create();
		noticeDialog.show();
	}

	/**
	 * 閺勫墽銇氭潪顖欐娑撳娴囩�纭呯樈濡楋拷
	 */
	private void showDownloadDialog()
	{
		// 閺嬪嫰锟芥潪顖欐娑撳娴囩�纭呯樈濡楋拷
		AlertDialog.Builder builder = new Builder(mContext);
		builder.setTitle(R.string.soft_updating);
		// 缂佹瑤绗呮潪钘夘嚠鐠囨繃顢嬫晶鐐插鏉╂稑瀹抽弶锟�		
		final LayoutInflater inflater = LayoutInflater.from(mContext);
		View v = inflater.inflate(R.layout.softupgrade_progress, null);
		mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
		builder.setView(v);
		// 閸欐牗绉烽弴瀛樻煀
		builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				// 鐠佸墽鐤嗛崣鏍ㄧХ閻樿埖锟�
				cancelUpdate = true;
			}
		});
		mDownloadDialog = builder.create();
		mDownloadDialog.setCancelable(false);
		mDownloadDialog.show();
		// 閻滄澘婀弬鍥︽
		downloadApk();
	}

	/**
	 * 娑撳娴嘺pk閺傚洣娆�
	 */
	private void downloadApk()
	{
		// 閸氼垰濮╅弬鎵殠缁嬪绗呮潪鍊熻拫娴狅拷
		new downloadApkThread().start();
	}

	/**
	 * 娑撳娴囬弬鍥︽缁捐法鈻�
	 */
	private class downloadApkThread extends Thread
	{
		@Override
		public void run()
		{
			try
			{
				// 閸掋倖鏌嘢D閸椻剝妲搁崥锕�摠閸︻煉绱濋獮鏈电瑬閺勵垰鎯侀崗閿嬫箒鐠囪鍟撻弶鍐
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
				{
					// 閼惧嘲绶辩�妯哄亶閸楋紕娈戠捄顖氱窞
					String sdpath = Environment.getExternalStorageDirectory() + "/";
					mSavePath = sdpath + "download";
					URL url = new URL(mHashMap.get("url"));
					// 閸掓稑缂撴潻鐐村复
					HttpURLConnection conn = (HttpURLConnection) url.openConnection();
					conn.connect();
					// 閼惧嘲褰囬弬鍥︽婢堆冪毈
					int length = conn.getContentLength();
					// 閸掓稑缂撴潏鎾冲弳濞达拷
					InputStream is = conn.getInputStream();

					File file = new File(mSavePath);
					// 閸掋倖鏌囬弬鍥︽閻╊喖缍嶉弰顖氭儊鐎涙ê婀�
					if (!file.exists())
					{
						file.mkdir();
					}
					File apkFile = new File(mSavePath, mHashMap.get("name"));
					FileOutputStream fos = new FileOutputStream(apkFile);
					int count = 0;
					// 缂傛挸鐡�
					byte buf[] = new byte[1024];
					// 閸愭瑥鍙嗛崚鐗堟瀮娴犳湹鑵�
					do
					{
						int numread = is.read(buf);
						count += numread;
						// 鐠侊紕鐣绘潻娑樺閺夆�缍呯純锟�						
						progress = (int) (((float) count / length) * 100);
						// 閺囧瓨鏌婃潻娑樺
						mHandler.sendEmptyMessage(DOWNLOAD);
						if (numread <= 0)
						{
							// 娑撳娴囩�灞惧灇
							mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
							break;
						}
						// 閸愭瑥鍙嗛弬鍥︽
						fos.write(buf, 0, numread);
					} while (!cancelUpdate);// 閻愮懓鍤崣鏍ㄧХ鐏忓崬浠犲顤嶇瑓鏉烇拷
					fos.close();
					is.close();
				}
			} catch (MalformedURLException e)
			{
				Utils.logStackTrace(e, TAG);
			} catch (IOException e)
			{
				Utils.logStackTrace(e, TAG);
			}
			// 閸欐牗绉锋稉瀣祰鐎电鐦藉鍡樻▔缁�拷
			mDownloadDialog.dismiss();
		}
	};

	/**
	 * 鐎瑰顥朅PK閺傚洣娆�
	 */
	private void installApk()
	{
		File apkfile = new File(mSavePath, mHashMap.get("name"));
		if (!apkfile.exists())
		{
			return;
		}
		// 闁俺绻僆ntent鐎瑰顥朅PK閺傚洣娆�
		Intent i = new Intent(Intent.ACTION_VIEW);
		i.setDataAndType(Uri.parse("file://" + apkfile.toString()), "application/vnd.android.package-archive");
		mContext.startActivity(i);
	}
}
