package com.gh.common.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import com.gh.common.constant.Config;
import com.gh.gamecenter.R;

import java.lang.reflect.Field;

public class Utils {

	private static final boolean DEBUG = true;
	private final static String TAG = "result";

	public static void log(String msg) {
		log(TAG, msg);
	}

	public static void log(Object obj) {
		log(TAG, obj.getClass().getSimpleName() + ":" + obj.toString());
	}

	public static void log(String tag, String msg) {
		log(Log.ERROR, tag, msg);
	}

	public static void log(String tag, Object obj) {
		log(Log.ERROR, tag, obj.getClass().getSimpleName() + ":" + obj.toString());
	}

	private static void log(int priority, String tag, String msg) {
		if (DEBUG) {
			Log.println(priority, tag, msg);
		}
	}

	private static void log(int priority, String tag, Object obj) {
		if (DEBUG) {
			Log.println(priority, tag, obj.getClass().getSimpleName() + ":" + obj.toString());
		}
	}

	public static void toast(Context context, String text) {
		Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
	}

	/*
	 * 获取服务器时间
	 */
	public static long getTime(Context context) {
		SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
		long serverTime = sp.getLong("server_time", 0);
		long clientTime = sp.getLong("client_time", 0);
		if (serverTime == 0 || clientTime == 0) {
			return System.currentTimeMillis() / 1000;
		} else {
			return serverTime + (System.currentTimeMillis() / 1000 - clientTime);
		}
	}

	public static void hideSoftInput(Context context, EditText editText) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
	}

	public static void showSoftInput(Context context, EditText editText) {
		InputMethodManager imm = (InputMethodManager) context
				.getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.showSoftInput(editText, InputMethodManager.SHOW_FORCED);
	}
	
	@SuppressWarnings("unchecked")
	public static <T extends View> T getView(View view, int id) {
		return (T) view.findViewById(id);
	}
	
	public static int getId(String name) {
		try {
			Class<?> arrayClass = R.id.class;
			for (Field field : arrayClass.getFields()) {
				if (field.getName().equals(name)) {
					return field.getInt(name);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;
	}

}
