package com.ubive.ui;

import java.io.IOException;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
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.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;
import com.ubive.BaseActivity;
import com.ubive.Global;
import com.ubive.R;
import com.ubive.biz.FarmBiz;
import com.ubive.entity.UpdateInfo;
import com.ubive.service.DownLoadApkService;
import com.ubive.ui.option.DisplayOption;
import com.ubive.util.ExitAppUtil;
import com.ubive.util.Logger;

public class MMoreActivity extends BaseActivity implements OnClickListener {
	 private static final String TAG = "SettingCenter";
	 ImageView ivNeedUpdate;
	 RelativeLayout rlUser;
	 RelativeLayout rlShare;
	 RelativeLayout rlScore;
	 RelativeLayout llChecknew;
	 RelativeLayout llAboutme;
	 TextView tvVersion,tvUsername;
	 FarmBiz  farmBiz;
	 int flagProbRight = Global.SETTING_EXIT;
	 private UpdateInfo updateInfo = null;
	 Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			hiderLoading();
			switch (msg.what) {
			case Global.NEED_NOT_UPDATE:
				showToast(R.string.version_no_need);
				initUpdateFlag(false);
				break;
			case Global.NEED_UPDATE:
				initUpdateFlag(true);
				flagProbRight = Global.SETTING_UPDATE;
				String info = updateInfo.description;
				for (String string:updateInfo.newfeature) {
					info+=string;
				}
				showBaseDialog(R.string.update_title, info, R.string.update, R.string.cancle);
				btDialogLeft.setOnClickListener(MMoreActivity.this);
				btDialogRigth.setOnClickListener(MMoreActivity.this);
				break;
			case Global.NET_UN_CONN:
				showToast(R.string.problem_net_un_conn);
				break;
			case Global.NET_PROBLEM:
				showToast(R.string.problem_check_new_fail);
				break;
			default:
				break;
			}
		}

		 
	 };
	@Override
	public void setUpView() {
		tvTitle = (TextView) findViewById(R.id.tv_model_title);
		tvTitle.setText(R.string.main_tag_more);
		
		ivNeedUpdate = (ImageView) findViewById(R.id.iv_need_update);
		rlUser = (RelativeLayout) findViewById(R.id.ll_setfarm_head);
		rlShare = (RelativeLayout) findViewById(R.id.ll_setfarm_tel);
		rlScore = (RelativeLayout) findViewById(R.id.ll_set_score);
		llChecknew = (RelativeLayout) findViewById(R.id.ll_setfarm_name);
		llAboutme = (RelativeLayout) findViewById(R.id.ll_setfarm_shop);
		
		tvVersion = (TextView) findViewById(R.id.tv_varsion);
		tvUsername = (TextView) findViewById(R.id.tv_name);
		boolean needUpdata = sp.getBoolean("needUpdate", false);
		initUpdateFlag(needUpdata);

		farmBiz = new FarmBiz(this);
	}

	private void initUpdateFlag(boolean needUpdata) {
		if(needUpdata){
			ivNeedUpdate.setVisibility(View.VISIBLE);
			tvVersion.setText("");
		}else{
			ivNeedUpdate.setVisibility(View.INVISIBLE);
			tvVersion.setText(getVersion());
		}
	}

	@Override
	public void addListener() {
		 rlUser.setOnClickListener(this);
		 rlShare.setOnClickListener(this);
		 rlScore.setOnClickListener(this);
		 llChecknew.setOnClickListener(this);
		 llAboutme.setOnClickListener(this);
	}

	@Override
	public void fillData() {
		int userid = sp.getInt("userid", Global.DEFAULT_USERID);
		if(userid!=Global.DEFAULT_USERID){
			String name = sp.getString("username", "");
			if (!TextUtils.isEmpty(name)) {
				if (name.length() > 15) {
					tvUsername.setText(name.substring(0, 14) + "...");
				} else {
					tvUsername.setText(name);
				}
			}
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		setContentView(R.layout.main_tab_setting);
		super.onCreate(savedInstanceState);
	}

	private void showExitDialog(int resInfoId) {
		showBaseDialog(R.string.point, resInfoId,R.string.confirm,R.string.cancle);
		btDialogLeft.setOnClickListener(this);
		btDialogRigth.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.bt_dialog_left:
			baseDialog.dismiss();
			switch (flagProbRight) {
			case Global.SETTING_EXIT:
				ExitAppUtil.exitApp(this);
				break;
			case Global.SETTING_UPDATE:
				showToast(R.string.point_loading_apk);
				loadApkFile();
				break;
			default:
				break;
			}
			break;
		case R.id.bt_dialog_right:
			baseDialog.dismiss();
			break;
		case R.id.ll_setfarm_head://¸öÈËÉèÖÃÐÅÏ¢½çÃæ
			goActivityAfterValid();
			break;
		case R.id.ll_setfarm_tel://·ÖÏí
			share();
			break;
		case R.id.ll_set_score://·ÖÏí
			goScore();
			break;
		case R.id.ll_setfarm_name://¼ì²é¸üÐÂ
			if(!isDoing()){
				checkVersion();
			}
			break;
		case R.id.ll_setfarm_shop:
			Bundle extra = new Bundle();
			extra.putString("version", getVersion());
			goTo(this, AboutUbiveActivity.class, extra);
			this.getParent().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
			break;
		default:
			break;
		}
	}
	private void goScore() {
		Uri uri = Uri.parse("market://details?id=" + this.getPackageName());
		Intent intent = new Intent(Intent.ACTION_VIEW,uri);
		try{
			startActivity(intent);
			this.getParent().overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
		}catch(ActivityNotFoundException e){
			showToast(R.string.problem_lunch_appstore_fail);
		}
	}

	
	private void goActivityAfterValid() {
		int userid = sp.getInt("userid", Global.DEFAULT_USERID);
		if(userid!=Global.DEFAULT_USERID){
			Intent intent = new Intent(this,SetUserInfoActivity.class);
			startActivityForResult(intent, 100);
			this.getParent().overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
		}else{
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra("fromWhat", Global.RLNAV_FROM_SETTING);		
			startActivityForResult(intent, 100);
			this.getParent().overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
		}
	}
	
	private void loadApkFile(){
		Intent intent = new Intent(this,DownLoadApkService.class);
		intent.putExtra("url",updateInfo.apkurl);
		startService(intent);
	}
	
	private void share() {
		Intent shareIntent = new Intent();
		shareIntent.setAction(Intent.ACTION_SEND);
		shareIntent.setType("text/plain");
		shareIntent.putExtra(Intent.EXTRA_SUBJECT, "·ÖÏí");
		String info = getResources().getString(R.string.setting_share);
		shareIntent.putExtra(Intent.EXTRA_TEXT,info);
		startActivity(shareIntent);
		this.getParent().overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_top);
	}

		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK) {
				flagProbRight = Global.SETTING_EXIT;
				showExitDialog(R.string.dialog_affirm_exit_ubive);
				return true;
			}
			return false;
		}

	    public String getVersion(){
	    	PackageManager manager = getPackageManager();
	    	try {
	    		PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
				return info.versionName;
			} catch (NameNotFoundException e) {
				e.printStackTrace();
				return "1.0.0";
			}
	    }
	
	    private void checkVersion(){
	    	if(!isNetConn()){//ÍøÂçÎÞÁ¬½Ó
				handler.sendEmptyMessage(Global.NET_UN_CONN);
				return;
	    	}
	    	final String version = getVersion();
			
			
			new AsyncTask<Integer, Void, UpdateInfo>() {

				@Override
				protected void onPostExecute(UpdateInfo result) {
					hiderLoading();
					if(result == null){
						showToast(R.string.problem_check_new_fail);
						return;
					}
					float serverVersion = Float.valueOf(result.version.replace(".", ""));
					float appVersion = Float.valueOf(version.replace(".",""));
					
					if(serverVersion>appVersion){
						handler.sendEmptyMessage(Global.NEED_UPDATE);
					}else{
						handler.sendEmptyMessage(Global.NEED_NOT_UPDATE);
					}
					super.onPostExecute(result);
				}

				@Override
				protected void onPreExecute() {
					showLoading(R.string.loading_check_new);
					super.onPreExecute();
				}

				@Override
				protected UpdateInfo doInBackground(Integer... params) {
					FarmBiz farmBiz = new FarmBiz(MMoreActivity.this);
					try {
						updateInfo = farmBiz.getUpdateInfo();
					} catch (IOException e) {
						e.printStackTrace();
						return null;
					}
					return updateInfo;
				}
			}.execute(0);
			
	
		}
		@Override
		protected void onActivityResult(int requestCode, int resultCode, Intent data) {
			switch (resultCode) {
			case Global.RET:
				break;
			case Global.RLNAV_FROM_SETTING:
				goActivityAfterValid();
				break;
			default:
				fillData();
				break;
			}
			super.onActivityResult(requestCode, resultCode, data);
		}
}
