package com.wasu.cs.ui;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.SparseArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.ImageView;
import android.widget.Scroller;
import android.widget.Toast;

import com.wasu.authsdk.DataUtils;
import com.wasu.comp.userlogin.DialogLogin;
import com.wasu.compfactory.WasuCompFactory;
import com.wasu.cs.adapter.GuideViewAdapter;
import com.wasu.module.log.WLog;

import java.io.IOException;
import java.lang.reflect.Field;

import cn.com.wasu.main.Common;
import cn.com.wasu.main.IntentMap;
import cn.com.wasu.main.R;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;

/**
 * 注册协议页
 *
 * @author Administrator
 *
 */
public class ActivityGuide extends ActivityBase {

	private static final String TAG = "ActivityGuide";

	public static final String FIRSTLAUNCH_KEY = "first_launch";

	private Context mContext;

	/**
	 * 具体开机页面
	 */
	private ViewPager mViewPager;
	/**
	 * 开机页面adapter
	 */
	private GuideViewAdapter mGuideAdapter;

	/**
	 * 当前第几页
	 */
	private int mCurrPageIndex;

	/**
	 * 統一登录页面
	 */
	private DialogLogin webPage;

	/**
	 * 总页数
	 * */
	private final int mTotalPage = 4;

	/**
	 * viewpage数组
	 */
	private SparseArray<View> guideViews;

	/**动态图内容*/
	SparseArray<GifImageView> mGifViews;
	SparseArray<ImageView> mLift, mRight;
	SparseArray<SparseArray> mBottom;
	GifDrawable g1,g2,g3,g0;
	/**
	 * 引导图片资源
	 */
	private final int[] pics = { R.mipmap.guide1, R.mipmap.guide2,
			R.mipmap.guide3, R.mipmap.guide4 };

	public interface OnVisibleChangeListener {
		void onVisibleChange(boolean isVisible);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		WLog.i(TAG,"onCreate()");
	}

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

	@Override
	protected void doCreate(Bundle savedInstanceState) {
		setContentView(R.layout.activity_guide);
		mContext = this;
		guideViews = new SparseArray<View>();

		for (int i=0; i < mTotalPage; i++){
			View v = getLayoutInflater().inflate(R.layout.activity_gif_guide, null);
			guideViews.put(i,v);
		}

		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		mViewPager.setOffscreenPageLimit(1);
		mViewPager.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

		// 通过反射修改viewpager的翻页速度
		try {
			Field field = ViewPager.class.getDeclaredField("mScroller");
			field.setAccessible(true);
			FixedSpeedScroller scroller = new FixedSpeedScroller(
					mViewPager.getContext(), new AccelerateInterpolator());
			field.set(mViewPager, scroller);
		} catch (Exception e) {
			e.printStackTrace();
		}

		// 动态图adapter
		initView();
	}

	private void initView(){
		mGuideAdapter = new GuideViewAdapter(guideViews, ActivityGuide.this);

		if (mGuideAdapter != null) {
			mViewPager.setAdapter(mGuideAdapter);
			// 当前只有4页，全部缓存起来，如果多的话，要去掉这行代码
//			mViewPager.setOffscreenPageLimit(mGuideAdapter.getCount());
		}

		/**初始化的动态view的内容**/
		mGifViews = new SparseArray<>();
		mLift = new SparseArray<>();
		mRight = new SparseArray<>();
		mBottom = new SparseArray<>();


		for (int i=0; i<mTotalPage; i++){
			GifImageView gifView = (GifImageView) guideViews.get(i).findViewById(R.id.gifview);
			ImageView imgLeft = (ImageView) guideViews.get(i).findViewById(R.id.img_left);
			ImageView imgRight = (ImageView) guideViews.get(i).findViewById(R.id.img_right);

			mGifViews.put(i,gifView);
			mLift.put(i,imgLeft);
			mRight.put(i,imgRight);

			SparseArray<ImageView> sp = new SparseArray();
			ImageView p1 = (ImageView) guideViews.get(i).findViewById(R.id.img1);
			sp.put(0,p1);
			ImageView p2 = (ImageView) guideViews.get(i).findViewById(R.id.img2);
			sp.put(1,p2);
			ImageView p3 = (ImageView) guideViews.get(i).findViewById(R.id.img3);
			sp.put(2,p3);
			ImageView p4 = (ImageView) guideViews.get(i).findViewById(R.id.img4);
			sp.put(3,p4);
			mBottom.put(i,sp);
		}

		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

			@Override
			public void onPageScrollStateChanged(int arg0) {

			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				mCurrPageIndex = arg0;
			}

			@Override
			public void onPageSelected(int arg1) {
				mLift.get(arg1).setVisibility(View.VISIBLE);
				mRight.get(arg1).setVisibility(View.VISIBLE);

				for (int i=0; i<mTotalPage; i++){ // 设置选中的point
					SparseArray<ImageView> sp = mBottom.get(arg1);
					if (i == arg1) {
						sp.get(i).setSelected(true);
					}

					if (i != arg1){
						mGifViews.get(arg1).setImageDrawable(null);
					}
				}

				switch (arg1){
					case 0:
						mLift.get(arg1).setVisibility(View.INVISIBLE);
						try {
							g0 = new GifDrawable(getResources(), pics[0]);
							mGifViews.get(arg1).setImageDrawable(g0);

							g1 = null;g2=null;g3=null;
						} catch (IOException e) {
							e.printStackTrace();
						}
//						mGifViews.get(arg1).setImageResource(pics[0]);
						break;
					case 1:
						try {
							g1 = new GifDrawable(getResources(), pics[1]);
							mGifViews.get(arg1).setImageDrawable(g1);

							g0 = null;g2=null;g3=null;
						} catch (IOException e) {
							e.printStackTrace();
						}
//						mGifViews.get(arg1).setImageResource(pics[1]);
						break;
					case 2:
						try {
							g2 = new GifDrawable(getResources(), pics[2]);
							mGifViews.get(arg1).setImageDrawable(g2);

							g1 = null;g0=null;g3=null;
						} catch (IOException e) {
							e.printStackTrace();
						}
//						mGifViews.get(arg1).setImageResource(pics[2]);
						break;
					case 3:
						try {
							g3 = new GifDrawable(getResources(), pics[3]);
							mGifViews.get(arg1).setImageDrawable(g3);

							g1 = null;g2=null;g0=null;
						} catch (IOException e) {
							e.printStackTrace();
						}
//						mGifViews.get(arg1).setImageResource(pics[3]);
						mRight.get(arg1).setVisibility(View.INVISIBLE);
						break;
				}
			}

		});

		// 设置首页样式
		try {
			g0 = new GifDrawable(getResources(), pics[0]);
			mGifViews.get(0).setImageDrawable(g0);

			mLift.get(0).setVisibility(View.INVISIBLE);
			mRight.get(0).setVisibility(View.VISIBLE);
//			mGifViews.get(0).setImageResource(pics[0]);
			SparseArray<ImageView> sp = mBottom.get(0);
			sp.get(0).setSelected(true);

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

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (webPage!=null && webPage.isShowing()) {
			// 如果是登录页面，不响应
			return true;
		}

		if (event.getAction() != KeyEvent.ACTION_DOWN){
			return super.dispatchKeyEvent(event);
		}

		final int keyCode = event.getKeyCode();
		final int pageCount = mGuideAdapter.getCount();
		switch (keyCode) {

			case KeyEvent.KEYCODE_DPAD_LEFT:

				return mViewPager.dispatchKeyEvent(event);

			case KeyEvent.KEYCODE_ENTER:
			case KeyEvent.KEYCODE_DPAD_CENTER:
				// 判断是不是引导页最后一张

				if (mCurrPageIndex == pageCount - 1) {
					// 如果是最后一张
					String userKey = DataUtils.load(mContext, "userKey");
					boolean isUserRegistered = userKey != null
							&& !"".equals(userKey.trim());

					// 用户已注册,退出引导，否则跳到注册页
					if (isUserRegistered) {
						IntentMap.startIntent(mContext, null, null, null,
								ActivityMain.class);
						this.finish();

					} else {
						// 统一登录页面
						if(webPage==null)
						webPage = new WasuCompFactory().createUniLogin(this, Common.loginurl);

						webPage.setLoginStatusListener(new DialogLogin.LoginStatusListener() {
							@Override
							public void onLogStatus(boolean arg0) {

								if (arg0) {
									// Toast.makeText(mContext, "登陆成功",
									// Toast.LENGTH_LONG).show();
								} else {
									Toast.makeText(mContext, "登录失败", Toast.LENGTH_LONG).show();
								}
								IntentMap.startIntent(mContext, null, null, null,
										ActivityMain.class);
								finish();
							}
						});
						// 跳到注册页
						webPage.show();

					}
				}
				return true;

			case KeyEvent.KEYCODE_DPAD_RIGHT:
				// 判断是不是引导页最后一张

				if (mCurrPageIndex == pageCount - 1) {
					IntentMap.startIntent(mContext, null, null, null,
							ActivityMain.class);
					this.finish();
					return true;
				} else {
					return mViewPager.dispatchKeyEvent(event);
				}

			default:
				return super.dispatchKeyEvent(event);
		}

	}

	/**
	 * 修正viewpager的滑动速度
	 *
	 * @author zhangrm@wasu.com
	 *
	 */
	class FixedSpeedScroller extends Scroller {
		// 默认400毫秒
		private int mDuration = 400;

		public FixedSpeedScroller(Context context) {
			super(context);
		}

		public FixedSpeedScroller(Context context, Interpolator interpolator) {
			super(context, interpolator);
		}

		@Override
		public void startScroll(int startX, int startY, int dx, int dy,
								int duration) {
			// Ignore received duration, use fixed one instead
			super.startScroll(startX, startY, dx, dy, mDuration);
		}

		@Override
		public void startScroll(int startX, int startY, int dx, int dy) {
			// Ignore received duration, use fixed one instead
			super.startScroll(startX, startY, dx, dy, mDuration);
		}

		public void setmDuration(int time) {
			mDuration = time;
		}

		public int getmDuration() {
			return mDuration;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (guideViews != null) {
			guideViews.clear();
			guideViews = null;
		}
		if (webPage != null) {
			webPage.cancel();
			webPage = null;
		}
		 if(mViewPager!=null){
			 mViewPager.removeAllViews();
			 mViewPager.setOnPageChangeListener(null);
			 mViewPager = null;
		 }

		if (g0 != null)
			g0.recycle();
		if (g1 !=null)
			g1.recycle();
		if (g2 != null)
			g2.recycle();
		if (g3 != null)
			g3.recycle();
	}
}