package com.gh.common.util;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

import com.gh.common.constant.Config;
import com.tencent.stat.StatConfig;

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

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class TokenUtils {

	// 注册设备
	public static synchronized String register(final Context context) {
		HashMap<String, String> params = new HashMap<>();
		String android_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
		if (!TextUtils.isEmpty(android_id)) {
			params.put("ANDROID_ID", android_id);
		}
		String imei = ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
		if (!TextUtils.isEmpty(imei)) {
			params.put("IMEI", imei);
		}
		WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
		String mac = wm.getConnectionInfo().getMacAddress();
		if (!TextUtils.isEmpty(mac)) {
			params.put("MAC", mac);
		} else {
			SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
			sp.edit().putBoolean("isUploadMac", false).apply();
		}
		String mid = StatConfig.getMid(context);
		if (!TextUtils.isEmpty(mid) || !"0".equals(mid)) {
			params.put("MTA_ID", mid);
		} else {
			SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
			sp.edit().putBoolean("isUploadMid", false).apply();
		}
		String url = "http://user.ghzhushou.com/v1d0/device/register";
		HttpURLConnection connection = null;
		try {
			JSONObject body = new JSONObject(params);
			connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("POST");

			connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
			connection.addRequestProperty("Device", DeviceUtils.getDeviceHeader(context));

			connection.connect();

			OutputStreamWriter outputStream = new OutputStreamWriter(
					connection.getOutputStream(), "utf-8");
			outputStream.write(body.toString());
			outputStream.flush();
			outputStream.close();

			if (connection.getResponseCode() == 200) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(connection.getInputStream()));
				StringBuilder builder = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				reader.close();

				try {
					JSONObject response = new JSONObject(builder.toString());
					String device_id = response.getString("device_id");
					// 保存device_id
					saveDeviceId(context, device_id);
					Utils.log("device_id = " + device_id);
					return device_id;
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	// 获取用户token
	public static synchronized String getToken(Context context) {
		SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE,
				Context.MODE_PRIVATE);
		String token = sp.getString("token", null);
		if (token != null) {
			long expire = sp.getLong("token_expire", 0) * 1000 - 10 * 1000;
			long time = System.currentTimeMillis();
			// 判断token是否过期
			if (time < expire) {
				// token未过期
				return token;
			}
		}

		// 重新获取token
		String url = "http://user.ghzhushou.com/v1d0/login";
		Map<String, String> params = new HashMap<>();
		params.put("device_id", getDeviceId(context));
		try {
			JSONObject body = new JSONObject(params);
			HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("POST");
			
			connection.addRequestProperty("Content-Type", "application/json; charset=utf-8");
			connection.addRequestProperty("Device", DeviceUtils.getDeviceHeader(context));

			connection.connect();

			OutputStreamWriter outputStream = new OutputStreamWriter(
					connection.getOutputStream(), "utf-8");
			outputStream.write(body.toString());
			outputStream.flush();
			outputStream.close();
			
			if (connection.getResponseCode() == 200) {
				BufferedReader reader = new BufferedReader(
						new InputStreamReader(connection.getInputStream()));
				StringBuilder builder = new StringBuilder();
				String line;
				while ((line = reader.readLine()) != null) {
					builder.append(line);
				}
				reader.close();
				try {
					Editor editor = sp.edit();
					JSONObject jsonObject = new JSONObject(builder.toString());
					editor.putString("user_name", jsonObject.getString("name"));
					editor.putString("user_icon", jsonObject.getString("icon"));
					jsonObject = jsonObject.getJSONObject("token");
					editor.putString("token", jsonObject.getString("value"));
					editor.putLong("token_expire", jsonObject.getLong("expire"));
					editor.apply();
					return jsonObject.getString("value");
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static synchronized void saveDeviceId(Context context, String device_id){
		saveSharedPreferences(context, device_id);
		saveDataFile(context, device_id);
		svaeSDCard(device_id, "/gh-uuid");//SDCard根目录
		svaeSDCard(device_id, "/system");//SDCard system目录
		svaeSDCard(device_id, "/data");//SDCard data目录
	}

	//将uuid存到sp
	private static void saveSharedPreferences(Context context, String device_id) {
		SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
		SharedPreferences.Editor edit = sp.edit();
		edit.putString("uuid", device_id);
		edit.apply();
		Utils.log("saveDeviceId", "保存成功SP");
	}

	//将uuid存到data/data/PackageName/files文件夹下
	private static void saveDataFile(Context context, String device_id) {
		FileOutputStream fops;
		try {
			fops = context.openFileOutput("uuid", Context.MODE_PRIVATE);
			fops.write(device_id.getBytes());
			fops.close();
			Utils.log("saveDeviceId", "保存成功DataFile");
		} catch (Exception e) {
			Utils.log("保存uuid到data/data/PackageName/files文件异常" + e.toString());
			e.printStackTrace();
		}
	}

	//将uuid存到SD卡
	private static void svaeSDCard(String device_id, String saveDir) {
		File sdCardDir  = Environment.getExternalStorageDirectory();
		String path = sdCardDir.getPath() + saveDir;

		File file = new File(path);
		if (!file.exists()){
			file.mkdirs();
		}

		// 判断文件是否存在，存在则删除
		File uuidFile = new File(path +"/uuid");
		if (uuidFile.isFile() && uuidFile.exists()){
			Utils.log(saveDir + "文件夹里的文件存在，执行删除操作");
			uuidFile.delete();
		}

		File writeFile = new File(file, "uuid");
		FileOutputStream fos;
		try {
			fos = new FileOutputStream(writeFile);
			fos.write(device_id.getBytes());
			fos.close();
			Utils.log("saveDeviceId", "保存成功SDCard"+"目录为："+saveDir);
		} catch (Exception e) {
			Utils.log("保存uuid到SDCard异常" + saveDir + e.toString());
			e.printStackTrace();
		}

	}

	// 启动助手时，检查uuid
	public static void checkDeviceID(Context context) {
		String uuid = loadSharedPreferences(context, false);
		if (uuid == null) {
			// 重新获取uuid，保存
			return;
		}
		// 检查
		if (loadSharedPreferences(context, true) == null){
			saveSharedPreferences(context, uuid);
		}
		if (loadDataFile(context ,true) == null){
			saveDataFile(context, uuid);
		}
		String[] dirName = {"/gh-uuid", "/system", "/data"};
		for (int i = 0; i< 3; i++) {
			String s = loadSDCard(dirName[i]);
			if (s == null) {
				svaeSDCard(uuid, dirName[i]);
			}
		}
	}

	public static synchronized String getDeviceId(Context context) {
		return loadSharedPreferences(context, false);
	}

	//读取SharedPreferences的uuid
	private static String loadSharedPreferences(Context context, boolean isCheck) {
		SharedPreferences sp = context.getSharedPreferences(Config.PREFERENCE, Context.MODE_PRIVATE);
		String uuid = sp.getString("uuid", null);
		if (isCheck){
			return uuid;
		}
		if (uuid == null){
			return loadDataFile(context, false);
		}
		Utils.log("getDeviceId", "获取成功SP" + uuid);
		return uuid;
	}

	//读取data/data/PackageName/files的uuid
	private static String loadDataFile(Context context, boolean isCheck) {
		File file = new File(context.getFilesDir(), "uuid");
		if (file.exists()){
			try {
				FileInputStream fis = new FileInputStream(file);
				byte[] b = new byte[1024];
				int count = -1;
				String uuid = null;
				while ((count = fis.read(b)) != -1) {
					uuid = new String(b, 0, count, "UTF-8");
				}
				Utils.log("getDeviceId", "获取成功DataFile"+ uuid);
				return uuid;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}else if (!isCheck){
			String[] dirName = {"/gh-uuid", "/system", "/data"};
			for (int i = 0; i< 3; i++) {
				String s = loadSDCard(dirName[i]);
				if (s != null) {
					return s;
				}
			}
		}
		return null;
	}

	//读取SD卡的uuid
	private static String loadSDCard(String saveDir){
		File sdCardDir  = Environment.getExternalStorageDirectory();
		String path = sdCardDir.getPath() + saveDir;
		File file = new File(path, "uuid");
		if (file.exists()){
			FileInputStream fis = null;
			ByteArrayOutputStream bos = null;
			try {
				fis = new FileInputStream(file);
				bos = new ByteArrayOutputStream();
				byte[] array = new byte[1024];
				int len = -1;
				while( (len = fis.read(array)) != -1){
					bos.write(array,0,len);
				}
				bos.close();
				fis.close();
				Utils.log("getDeviceId", "获取成功SDCard"+"目录为："+saveDir+"::"+bos.toString());
				return bos.toString();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}

}
