package com.wasu.cs.ui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.wasu.authsdk.AuthListener;
import com.wasu.authsdk.AuthSDK;
import com.wasu.common.WError;
import com.wasu.comp.ad.ADComp.onAdFetchListener;
import com.wasu.comp.ad.AdView;
import com.wasu.comp.ad.AdViewListener;
import com.wasu.comp.ad.WasuAdEngine;
import com.wasu.cs.image.MyImageLoader;
import com.wasu.module.datafetch.DataFetchListener.JsonListener;
import com.wasu.module.datafetch.DataFetchListener.ObjectListener;
import com.wasu.module.datafetch.DataFetchModule;
import com.wasu.module.log.WLog;
import com.wasu.statistics.WasuStatistics;
import com.wasu.vast.model.AdExtension;

import org.json.JSONObject;

import basic.update.present.UpdatePresent;
import basic.update.view.AppStartUpdateView;
import cn.com.wasu.main.Common;
import cn.com.wasu.main.ErrorMap;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;

public class ActivityWelcome extends ActivityBase {
	private String TAG = "ActivityWelcome";

	private Context mContext;
	// private ImageView mAdView;
	private TextView mVersionView;
	private boolean mbTimerReady = false;
	private static final int BOOT_DURATION = 3 * 1000; // 3s
	private final String BOOT_AD_PIC = "boot_ad.png";

	private Bitmap bmp;
	// 缓存中的图片资源
	private Bitmap bmpCache;
	private String adPicUrl = "";
	private final int DOWLOAD_OK = 111;
	private final int SAVE_OK = 222;
	/**
	 * 开机广告id
	 */
	private ObjectListener mObjectListener;
	private onAdFetchListener mOnAdFetchListener;
	private AuthListener registerDeviceListener;
	private AuthListener loginDeviceListener;

	private RelativeLayout adContent;

	private String mHomePreload = null;

	// 不需要检测授权，内部自己授权
	@Override
	protected int checkAuthState() {
		return AUTH_CHECK_CANCEL;
	}

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		WLog.i(TAG,"doCreate()");

		setContentView(R.layout.activity_welcome);
		mContext = this;

		initView();
		initData();

		//check wether need to update
		UpdatePresent.getInstance().checkWhetherNeedUpdate(new AppStartUpdateView());
	}

	private void initView() {

		// mAdView = (ImageView) findViewById(R.id.ivWelcome);
		adContent = (RelativeLayout) findViewById(R.id.adcontent);
		mVersionView = (TextView) findViewById(R.id.tvVersion);

	}

	private void initData() {
		preloadHomeData();

		// 如果本地缓存的没有，加载默认图片
		// if (TextUtils
		// .isEmpty(ConfigUtils.getString(mContext, null, BOOT_AD_ID))) {
		// mAdView.setImageBitmap(readBitMap(this, R.drawable.default_boot));
		// } else {// 如果本地有缓存，读取缓存中的图片
		// bmpCache = MyImageLoader.useTheImage(mContext, BOOT_AD_PIC);
		// if (bmpCache != null) {
		// mAdView.setImageBitmap(bmpCache);
		// } else {
		// ConfigUtils.saveData(mContext, null, BOOT_AD_ID, "");
		// mAdView.setImageBitmap(readBitMap(this, R.drawable.default_boot));
		// }
		//
		// }
		WasuAdEngine.getInstance().removeDirectP();

		AdView adView = WasuAdEngine.getInstance().getImageAd(69, 0, false, null, new AdViewListener() {

			@Override
			public void AdUserClose() {
				// TODO Auto-generated method stub

			}

			@Override
			public void AdPause() {

			}

			@Override
			public void AdResume() {

			}

			@Override
			public void AdStopped() {
				// TODO Auto-generated method stub

			}

			@Override
			public void AdSkipped() {
				// TODO Auto-generated method stub

			}

			@Override
			public void AdLoaded(AdView.Property property) {
				// TODO Auto-generated method stub

			}

			@Override
			public void AdStarted(AdExtension adExtension) {

			}

			@SuppressLint("NewApi")
			@Override
			public void AdError() {
				// TODO Auto-generated method stub

				adContent.setBackgroundResource(R.drawable.default_boot);
			}

			@Override
			public void AdClickThru(AdExtension adExtension) {

			}
		});
		if (adView != null) {
			adContent.addView(adView);
		}

		showVersion();
		// 检查设备登陆状态
		if (!AuthSDK.getInstance().isDeviceRegister()) {
			registerDevice();
		} else if (!AuthSDK.getInstance().isDeviceLogin()) {
			authDevice();
		}
		// loadBootAdPic();
		// 设置3秒超时
		adContent.postDelayed(adGoneRunnable, BOOT_DURATION);
	}

	private void preloadHomeData() {
		DataFetchModule.getInstance().fetchJsonGet(Common.HOME_URL, new JsonListener() {

			@Override
			public void onJsonGet(int arg0, String arg1, JSONObject arg2) {
				if (arg0 == WError.ERROR_NONE && arg2 != null) {
					mHomePreload = arg2.toString();
				}
			}
		});
	}

	Runnable adGoneRunnable = new Runnable() {
		@Override
		public void run() {
			mbTimerReady = true;
			if (AuthSDK.getInstance().isDeviceLogin()) {
				openNextActivity();
			}
		}
	};

	private void registerDevice() {
		if (registerDeviceListener != null) {
			registerDeviceListener = null;
		}
		registerDeviceListener = new AuthListener() {
			@Override
			public void result(int arg0, String arg1, Object arg2) {
				String success = "0";
				if (arg0 == WError.ERROR_NONE) {
					authDevice();
					success = "1";
				} else {
					// 错误界面
					success = "0";
					if (arg0 == WError.ERROR_UPM_NOT_AUTH) {
						IntentMap.startIntent(ActivityWelcome.this, null, null, null, ActivityServiceStop.class);
						finish();
					} else {
						showErrorExitDlg(ErrorMap.mapError(ActivityWelcome.this, arg0, arg1));
					}
				}
				WasuStatistics.getInstance().registEnd(success);
			}
		};
		WasuStatistics.getInstance().registBegin();
		AuthSDK.getInstance().deviceRegister(registerDeviceListener);
	}

	private void authDevice() {
		if (loginDeviceListener != null) {
			loginDeviceListener = null;
		}
		loginDeviceListener = new AuthListener() {
			@Override
			public void result(int rescode, String resMes, Object arg2) {
				String success = "0";
				if (rescode == WError.ERROR_NONE) {
					success = "1";
					if (mbTimerReady) {
						openNextActivity();
					}
				} else {
					// 错误界面

					success = "0";
					if (rescode == WError.ERROR_UPM_NOT_AUTH) {
						IntentMap.startIntent(ActivityWelcome.this, null, null, null, ActivityServiceStop.class);
						finish();
					} else {
						showErrorExitDlg(ErrorMap.mapError(ActivityWelcome.this, rescode, resMes));
					}
				}
				WasuStatistics.getInstance().loadEnd(success);
			}
		};
		WasuStatistics.getInstance().loadBegin();
		AuthSDK.getInstance().deviceLogin(loginDeviceListener);
	}

	private Handler messageHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SAVE_OK:
				// 保存到本地成功
				break;
			case DOWLOAD_OK:
				// 下载成功
				if (savePicRunnable != null) {
					new Thread(savePicRunnable).start();
				}
				break;
			default:
				break;
			}

		}
	};
	private Runnable savePicRunnable = new Runnable() {
		@Override
		public void run() {
			MyImageLoader.saveFile(mContext, bmp, BOOT_AD_PIC);
			if (messageHandler != null) {
				messageHandler.sendEmptyMessage(SAVE_OK);
			}

		}

	};

	private Runnable getPicRunnable = new Runnable() {
		@Override
		public void run() {
			try {

				bmp = MyImageLoader.loadImageFromUrl(adPicUrl);
				if (messageHandler != null) {
					messageHandler.sendEmptyMessage(DOWLOAD_OK);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	};

	// public void loadBootAdPic() {
	//
	// final ADComp adComp = new WasuCompFactory().createCompAd(mContext);
	// Map<String, String> params = new HashMap<String, String>();
	// params.put("userid",
	// AuthSDK.getInstance().getValue(IAuthInterface.KEY_TVID));
	//
	// // 先判断缓存里有没有
	// if (adComp.getAd() != null
	// && !TextUtils.isEmpty(adComp.getAd().getBoot())) {
	//
	// adComp.getAd().updateParam(params);
	// getAdPic(adComp.getAd().getBoot());
	//
	// } else {
	//
	// if (mOnAdFetchListener != null) {
	// mOnAdFetchListener = null;
	// }
	//
	// mOnAdFetchListener = new onAdFetchListener() {
	//
	// @Override
	// public void onAdFetchResult(int retcode, String extraMsg) {
	//
	// if (retcode == 0) {
	//
	// getAdPic(adComp.getAd().getBoot());
	// }
	// }
	// };
	//
	// adComp.fetchAdGet(BuildType.AD, params, mOnAdFetchListener);
	// }
	// }

	// private void getAdPic(String url) {
	//
	// if (mObjectListener != null) {
	// mObjectListener = null;
	// }
	// mObjectListener = new ObjectListener() {
	//
	// @Override
	// public void onObjectGet(int retcode, String extraMsg,
	// ObjectBase data) {
	//
	// if (retcode == 0) {
	// AdBoot adData = (AdBoot) data;
	// adPicUrl = adData.getVerSrc();
	// if (!TextUtils.isEmpty(adData.getVerId())) {
	// // 比较广告id与本地id
	// if (!adData.getVerId().equals(
	// ConfigUtils.getString(mContext, null,
	// BOOT_AD_ID))) {
	// // 如果不同，则下载后存到本地
	// ConfigUtils.saveData(mContext, null, BOOT_AD_ID,
	// adData.getVerId());
	// new Thread(getPicRunnable).start();
	// }
	// }
	// }
	// }
	// };
	// DataFetchModule.getInstance().fetchObjectGet(url, AdBoot.class,
	// mObjectListener);
	// }

	private void showVersion() {
		try {
			mVersionView.setText("version:" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
		} catch (NameNotFoundException e) {

		}
	}

	/**
	 * 打开下一个
	 */
	private void openNextActivity() {
		Intent i = new Intent();
		i.putExtra("preload", "" + mHomePreload);
		IntentMap.startIntent(ActivityWelcome.this, i, null, null, ActivityMain.class);
		finish();
	}

	@Override
	protected void onDestroy() {
		if (bmp != null) {
			bmp.recycle();
		}
		if (bmpCache != null) {
			bmpCache.recycle();
		}
		if (registerDeviceListener != null) {
			registerDeviceListener = null;
		}
		if (loginDeviceListener != null) {
			loginDeviceListener = null;
		}
		if (adContent != null) {
			adContent.removeCallbacks(adGoneRunnable);
			adContent.removeAllViews();
		}
		if (adGoneRunnable != null) {
			adGoneRunnable = null;
		}
		if (getPicRunnable != null) {
			getPicRunnable = null;
		}
		if (savePicRunnable != null) {
			savePicRunnable = null;
		}
		if (messageHandler != null) {
			messageHandler.removeMessages(DOWLOAD_OK);
			messageHandler.removeMessages(SAVE_OK);
			messageHandler = null;
		}
		if (mObjectListener != null) {
			mObjectListener = null;
		}
		if (mOnAdFetchListener != null) {
			mOnAdFetchListener = null;
		}
		super.onDestroy();
	}
}
