package com.gh.gamecenter;

import android.app.ActionBar;
import android.app.ActionBar.LayoutParams;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.gh.base.AppController;
import com.gh.base.BaseActivity;
import com.gh.common.constant.Config;
import com.gh.common.constant.Constants;
import com.gh.common.util.FileUtils;
import com.gh.common.util.ImageUtils;
import com.gh.common.util.PackageUtils;
import com.gh.common.util.TimestampUtils;
import com.gh.common.util.Utils;
import com.gh.gamecenter.db.info.FilterInfo;
import com.gh.gamecenter.eventbus.EBReuse;
import com.gh.gamecenter.manager.DataCollectionManager;
import com.gh.gamecenter.manager.FilterManager;
import com.gh.gamecenter.volley.extended.JsonArrayExtendedRequest;
import com.gh.gamecenter.volley.extended.JsonObjectExtendedRequest;
import com.gh.gamecenter.volley.extended.StringExtendedRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import de.greenrobot.event.EventBus;

/**
 * 引导页面
 * 
 * @author 黄壮华
 * 
 */
public class SplashScreenActivity extends BaseActivity {

	public static final String TAG = SplashScreenActivity.class.getSimpleName();

	private SharedPreferences sp;

	private String from;

	private long start;

	private boolean isFirst;

	private Handler handler = new Handler();

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

		start = System.currentTimeMillis();

		isFirst = true;

		sp = getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);

		from = getIntent().getStringExtra("from");

		if (sp.getBoolean("isNewFirstLaunch", true)
				|| sp.getInt("actionbar_height", 0) != 0) {
			setTheme(R.style.AppTheme_Guide);
		} else {
			setTheme(R.style.AppTheme_Fullscreen);
			// 自定义ActionBar
			ActionBar mActionBar = getActionBar();
			if (mActionBar != null) {
				mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
				RelativeLayout relativeLayout = new RelativeLayout(this);
				relativeLayout.setBackgroundResource(R.color.theme);
				LayoutParams params = new LayoutParams(
						LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
				mActionBar.setCustomView(relativeLayout, params);// 自定义ActionBar布局
			}
		}

		if (sp.getBoolean("isNewFirstLaunch", true)) {
			setContentView(R.layout.activity_splash_intro);
			ViewPager splash_viewPager = (ViewPager) findViewById(R.id.splash_viewPager);
			splash_viewPager.setAdapter(new ViewPagerAdapter());
		} else {
			setContentView(R.layout.activity_splash_normal);
		}
	}

	private class ViewPagerAdapter extends PagerAdapter {

		private int[] pics = { R.drawable.splash_01, R.drawable.splash_02,
				R.drawable.splash_03, R.drawable.splash_04 };

		@Override
		public int getCount() {
			return pics.length;
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			if (position == pics.length - 1) {
				View view = View.inflate(SplashScreenActivity.this, R.layout.splash_viewpage_item, null);
				TextView textView = (TextView) view.findViewById(R.id.splash_viewPager_item_btn);
				DisplayMetrics outMetrics = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
				RelativeLayout.LayoutParams rparams = (RelativeLayout.LayoutParams) textView.getLayoutParams();
				rparams.height = outMetrics.heightPixels / 4;
				textView.setLayoutParams(rparams);
				textView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						launch();
					}
				});
				container.addView(view);
				return view;
			} else {
				ImageView imageView = new ImageView(SplashScreenActivity.this);
				ImageUtils.getInstance(SplashScreenActivity.this).
						display("drawable://" + pics[position], imageView, -1);
				container.addView(imageView);
				return imageView;
			}
		}

		@Override
		public boolean isViewFromObject(View view, Object object) {
			return view == object;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView((View) object);
		}

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			if (sp.getBoolean("isNewFirstLaunch", true)) {
				launch();
			} else {
				return true;
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		if (hasFocus && isFirst) {
			isFirst = false;

			// 第一次启动，把package.txt文件内容加载进数据库
			if (!sp.getBoolean("isLoadFilter", false)) {
				try {
					List<FilterInfo> list = new ArrayList<>();
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(getAssets().open("package.txt")));
					String line;
					while ((line = reader.readLine()) != null) {
						list.add(new FilterInfo(line));
					}
					reader.close();
					FilterManager filterManager = new FilterManager(getApplicationContext());
					filterManager.addAllFilter(list);
					sp.edit().putBoolean("isLoadFilter", true).apply();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			checkGhFile();

			/*
			 * 更新过滤表，获取自动刷新的cd，获取版本对应表
			 */
			String time = sp.getString("filter_time", null);
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			String today = format.format(new Date());
			if (!today.equals(time)) {
				FilterManager manager = new FilterManager(getApplicationContext());
				manager.getFilterFromServer(today);

				// 获取版本代码、名称
				getPlatform();
			}

			// 获取下载按钮状态、开启or关闭
			getDownloadStatus();

			getUISetting();

			getTime();

			/*
			 * 上传数据
			 */
			DataCollectionManager.getInstance(getApplicationContext()).upload();

			// 不是第一次启动
			if (!sp.getBoolean("isNewFirstLaunch", true)) {
				int height = sp.getInt("actionbar_height", 0);
				if (height == 0) {
					final ActionBar actionBar = getActionBar();
					if (actionBar != null) {
						sp.edit().putInt("actionbar_height", actionBar.getHeight()).apply();
					}
				}

				long end = System.currentTimeMillis() - start;
				if (end < 3000) {
					handler.postDelayed(new Runnable() {
						@Override
						public void run() {
							launch();
						}
					}, 3000 - end);
				} else {
					launch();
				}
			}
		}
	}

	/*
	 * 获取服务器时间
	 */
	private void getTime() {
		StringExtendedRequest request = new StringExtendedRequest(
				Request.Method.GET, Config.HOST + "v2d0/support/time/current",
				new Response.Listener<String>() {
					@Override
					public void onResponse(String response) {
						Editor editor = sp.edit();
						editor.putLong("server_time", Long.parseLong(response));
						editor.putLong("client_time", System.currentTimeMillis() / 1000);
						editor.apply();
					}
				}, null);
		request.setShouldCache(false);
		AppController.addToRequestQueue(request, TAG);
	}

	/*
	 * 获取界面设置
	 */
	private void getUISetting() {
		JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
				Config.HOST + "v1d45/support/setting/ui",
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						Utils.log(response.toString());
						try {
							Editor editor = sp.edit();
							editor.putInt("download_box_row",
									response.getJSONObject("download_box").getInt("row"));
							editor.putInt("download_box_column",
									response.getJSONObject("download_box").getInt("column"));
							editor.putInt("game_detail_news_type_tab_column",
									response.getJSONObject("game_detail_news_type_tab").getInt("column"));
							editor.apply();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, null);
		AppController.addToRequestQueue(request, TAG);
	}

	/*
	 * 获取下载按钮显示状态
	 */
	private void getDownloadStatus() {
		String TD_CHANNEL_ID = (String) PackageUtils.getMetaData(this,
				getPackageName(), "TD_CHANNEL_ID");
		JsonObjectExtendedRequest request = new JsonObjectExtendedRequest(
				Config.HOST + "v1d45/support/setting/download/" + TD_CHANNEL_ID
						+ "/switch2?version="
						+ PackageUtils.getVersion(getApplicationContext()),
				new Response.Listener<JSONObject>() {
					@Override
					public void onResponse(JSONObject response) {
						try {
							boolean isShow = response.getBoolean("status");
							sp.edit().putBoolean("isShow", isShow).apply();
							EventBus.getDefault().post(new EBReuse("Refresh"));
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, null);
		AppController.addToRequestQueue(request, TAG);
	}

	/*
	 * 检查下载文件夹下是否有旧版本的光环助手的包，有则删除
	 */
	private void checkGhFile() {
		File folder = new File(FileUtils.getDownloadDir(this) + File.separator);
		if (folder.isDirectory()) {
			for (File file : folder.listFiles()) {
				if (!file.isDirectory() && file.getName().startsWith("光环助手V")) {
					String name = file.getName();
					int index = name.indexOf("_");
					if (index != -1) {
						float version = Float.valueOf(name.substring(
								name.indexOf("V") + 1, index));
						float currentVersion = Float.valueOf(PackageUtils
								.getVersion(getApplicationContext()));
						if (version <= currentVersion) {
							file.delete();
						}
					}
				}
			}
		}
	}

	private void getPlatform() {
		JsonArrayExtendedRequest request = new JsonArrayExtendedRequest(
				TimestampUtils.addTimestamp(
						Config.HOST + "v1d45/support/setting/platform",
						Constants.PLATFORM_CD),
				new Response.Listener<JSONArray>() {
					@Override
					public void onResponse(JSONArray response) {
						try {
							Set<String> pset = new HashSet<>();
							for (int i = 0; i < response.length(); i++) {
								JSONObject jsonObject = response
										.getJSONObject(i);
								String code = jsonObject.getString("code");
								String name = jsonObject.getString("name");
								String pic = jsonObject.getString("pic");
								String color = jsonObject.getString("color");
								pset.add(code + "=" + name + "=" + pic + "="
										+ color);
							}
							SharedPreferences sharedPreferences = getSharedPreferences(
									"gh_platform", Context.MODE_PRIVATE);
							Editor editor = sharedPreferences.edit();
							editor.putStringSet("platform", pset);
							editor.apply();
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}, null);
		AppController.addToRequestQueue(request, TAG);
	}

	// 跳转到主界面
	private void launch() {
		Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);

		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.getString("to") != null) {
			intentControl(bundle, intent);
		} else {
			intent.putExtra("from", from);
			if ("plugin".equals(from)) {
				intent.putExtra("packageName", getIntent().getStringExtra("packageName"));
			} else if ("mipush_news".equals(from)) {
				intent.putExtra("entity", getIntent().getSerializableExtra("entity"));
			} else if ("mipush_plugin".equals(from)) {
				intent.putExtra("data", getIntent().getStringExtra("data"));
			} else if ("plugin_install".equals(from)) {
				intent.putExtra("path", getIntent().getStringExtra("path"));
			}
		}

		startActivity(intent);
		finish();
	}

	private void intentControl(Bundle bundle, Intent intent) {
		String to = bundle.getString("to");
		if ("NewsActivity".equals(to)) {
			intent.putExtra("newsId", bundle.getString("newsId"));
			intent.putExtra("entrance", bundle.getString("entrance"));
		} else if("DownloadManagerActivity".equals(to)) {
			intent.putExtra("packageName", bundle.getString("packageName"));
		} else if ("GameDetailsActivity".equals(to)) {
			intent.putExtra("gameId", bundle.getString("gameId"));
			intent.putExtra("entrance", bundle.getString("entrance"));
		} else if ("SubjectActivity".equals(to)) {
			intent.putExtra("id", bundle.getString("id"));
			intent.putExtra("name", bundle.getString("name"));
			intent.putExtra("order", bundle.getBoolean("order"));
		} else if ("ViewImageActivity".equals(to)) {
			intent.putExtra("urls", bundle.getStringArrayList("urls"));
			intent.putExtra("current", bundle.getInt("current",0));
			intent.putExtra("ScaleType", bundle.getString("ScaleType"));
		}
		if ("NewsActivity".equals(to)) {
			intent.putExtra("to", "NewsDetailActivity");
		} else if ("GameDetailsActivity".equals(to)) {
			intent.putExtra("to", "GameDetailActivity");
		} else {
			intent.putExtra("to", to);
		}
	}

}
