package com.iamberry.app.ulitity;

import static com.iamberry.app.config.ImberryConfig.SMS_PASSWORD;
import static com.iamberry.app.config.ImberryConfig.SMS_TEXT;
import static com.iamberry.app.config.ImberryConfig.SMS_URL;
import static com.iamberry.app.config.ImberryConfig.SMS_USERNAME;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.iamberry.app.config.Constants;
import com.iamberry.app.core.dto.RecordDTO;
import com.iamberry.app.tool.dto.AddressDTO;
import com.iamberry.app.tool.util.HttpUtility;
import com.iamberry.app.tool.util.JsonParseUtil;
import com.iamberry.app.tool.util.Result;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

public class Utility {

	public static String DATA_STORE = "";
	private static final String AB = "123456789abcdefghijklmnpqrstuvwxyz";

	private static Random rnd = new Random();

	public static String getDateByDay() {
		Calendar cal = Calendar.getInstance();
		StringBuffer buffer = new StringBuffer();
		buffer.append(cal.get(Calendar.YEAR));
		buffer.append(cal.get(Calendar.MONTH) + 1);
		buffer.append(cal.get(Calendar.DAY_OF_MONTH));
		return buffer.toString();
	}

	public static boolean contains(String[] array, String item) {
		try {
			for (int i = 0; i < array.length; i++) {
				if (array[i].equals(item)) {
					return true;
				}
			}
		} catch (Exception ex) {

		}
		return false;
	}

	public static String normalizePath(String path) {
		return path.replace("\\\\", "\\").replace("\\", "/").replace("//", "/").replace("..", ".");
	}

	public static String getRandomString(int len) {
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append(AB.charAt(rnd.nextInt(AB.length())));
		return sb.toString();
	}

	public static int CalculateAge(Long date) {
		Date birthDate = new Date(0);
		if (date != null)
			birthDate = new Date(date);
		SimpleDateFormat format = new SimpleDateFormat("yyyy");
		int birthYear = Integer.parseInt(format.format(birthDate));
		int currentYear = Integer.parseInt(format.format(new Date(System.currentTimeMillis())));
		int age = currentYear - birthYear;

		return age;
	}

	public static List<RecordDTO> convertMap(List<Map<String, Object>> list, String dateType) {
		List<RecordDTO> maps = new ArrayList<RecordDTO>();
		try {
			SimpleDateFormat sdf = null;
			for (Map<String, Object> map : list) {
				switch (dateType) {
				case "days":
					sdf = new SimpleDateFormat("yyyyMMddHH");
					break;
				case "weeks":
					sdf = new SimpleDateFormat("yyyyMMdd");
					break;
				case "years":
					sdf = new SimpleDateFormat("yyyyMM");
					break;
				}
				Date key = sdf.parse(map.get(dateType).toString());
				Double value = Double.parseDouble(map.get("volume").toString());
				maps.add(new RecordDTO(key.getTime(), value));
			}
		} catch (Exception e) {
		}
		return maps;
	}

	public static Map<String, List<RecordDTO>> synAppMachineRecord(Map<String, List<RecordDTO>> oldMap) {
		Map<String, List<RecordDTO>> synMap = oldMap;
		int appSize = synMap.get("app").size();
		int machineSize = synMap.get("machine").size();
		int signer = 0;
		long appDate = 0l, machineDate = 0l;
		RecordDTO appRecord, machineRecord;
		for (int i = 0; i < appSize && i < machineSize; i++) {
			appRecord = synMap.get("app").get(i);
			machineRecord = synMap.get("machine").get(signer);
			appDate = appRecord.getRecordDate();
			machineDate = machineRecord.getRecordDate();
			if (appDate == machineDate) {
				signer++;
			} else if (appDate < machineDate) {
				synMap.get("machine").add(i, new RecordDTO(appDate, 0));
				machineSize++;
				signer++;
			} else {
				synMap.get("app").add(signer, new RecordDTO(machineDate, 0));
				appSize++;
				signer++;
			}
		}
		while (signer < machineSize) {
			synMap.get("app").add(new RecordDTO(synMap.get("machine").get(signer).getRecordDate(), 0));
			signer++;
		}
		while (signer < appSize) {
			synMap.get("machine").add(new RecordDTO(synMap.get("app").get(signer).getRecordDate(), 0));
			signer++;
		}
		return synMap;
	}

	public static Map<String, List<RecordDTO>> fillAppMachineRecordWithZero(Map<String, List<RecordDTO>> synedMap, String dataType,
			String chosenDate) {
		Map<String, List<RecordDTO>> fillMap = synedMap;
		Calendar calendar = Calendar.getInstance();
		List<Integer> existTimePoint = new ArrayList<Integer>();
		long timePoint = 0l;
		switch (dataType) {
		case "days":
			if (fillMap.get("app").isEmpty()) {
				calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
			}
			fillMap.get("app").forEach(record -> {
				calendar.setTime(new Date(record.getRecordDate()));
				existTimePoint.add(calendar.get(Calendar.HOUR_OF_DAY));
			});
			for (int i = 0; i < 24; i++) {
				if (!existTimePoint.remove(new Integer(i))) {
					calendar.set(Calendar.HOUR_OF_DAY, i);
					timePoint = calendar.getTimeInMillis();
					fillMap.get("app").add(i, new RecordDTO(timePoint, 0));
					fillMap.get("machine").add(i, new RecordDTO(timePoint, 0));
				}
			}
			break;
		case "weeks":
			if (fillMap.get("app").isEmpty()) {
				calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
			}
			fillMap.get("app").forEach(record -> {
				calendar.setTime(new Date(record.getRecordDate()));
				existTimePoint.add(calendar.get(Calendar.DAY_OF_WEEK));
			});
			if (existTimePoint.contains(new Integer(1))) {
				calendar.add(Calendar.DATE, -7);
			}
			for (int i = 2; i <= 7; i++) {
				if (!existTimePoint.remove(new Integer(i))) {
					calendar.set(Calendar.DAY_OF_WEEK, i);
					timePoint = calendar.getTimeInMillis();
					fillMap.get("app").add(i - 2, new RecordDTO(timePoint, 0));
					fillMap.get("machine").add(i - 2, new RecordDTO(timePoint, 0));
				}
			}
			if (!existTimePoint.contains(new Integer(1))) {
				calendar.add(Calendar.DATE, 7);
				calendar.set(Calendar.DAY_OF_WEEK, 1);
				timePoint = calendar.getTimeInMillis();
				fillMap.get("app").add(new RecordDTO(timePoint, 0));
				fillMap.get("machine").add(new RecordDTO(timePoint, 0));
			}
			break;
		case "years":
			if (fillMap.get("app").isEmpty()) {
				calendar.setTime(Utility.formatStringToDate("yyyy-MM-dd HH:mm:ss", chosenDate));
			}
			fillMap.get("app").forEach(record -> {
				calendar.setTime(new Date(record.getRecordDate()));
				existTimePoint.add(calendar.get(Calendar.MONTH));
			});
			for (int i = 0; i <= 11; i++) {
				if (!existTimePoint.remove(new Integer(i))) {
					calendar.set(Calendar.MONTH, i);
					timePoint = calendar.getTimeInMillis();
					fillMap.get("app").add(i, new RecordDTO(timePoint, 0));
					fillMap.get("machine").add(i, new RecordDTO(timePoint, 0));
				}
			}
			break;
		}
		return fillMap;
	}

	public static String getRandomCode(int len) {
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++)
			sb.append("0123456789".charAt(rnd.nextInt("0123456789".length())));
		return sb.toString();
	}

	public static String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	public static String CDN_WRITE_BASE_64_URL = "http://cms.iamberry.com/open-cdn/ssl/data/write/base64";

	public static String uploadBase64File(String base64Data, String path) {
		try {
			if (base64Data != null) {
				StringBody pic = new StringBody(base64Data, ContentType.DEFAULT_TEXT);
				StringBody type = new StringBody("jpg", ContentType.TEXT_PLAIN);
				HttpEntity entity = MultipartEntityBuilder.create().addPart("type", type).addPart("base64data", pic)
						.build();
				String result = HttpUtility.httpsPost(CDN_WRITE_BASE_64_URL, entity);

				JSONObject json = new JSONObject(result);
				int requestSatus = json.getJSONObject("header").getInt("status");
				if (1000 == requestSatus) {
					path = json.getJSONObject("data").get("url").toString();
				}

				return path;
			}
		} catch (Exception e) {
			return null;
		}
		return "";
	}

	public static String readFile(InputStream in) {
		BufferedReader reader = null;
		String result = "";
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(in, "UTF-8");
			reader = new BufferedReader(inputStreamReader);
			String tempString = null;
			while ((tempString = reader.readLine()) != null) {
				result += tempString;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result;
	}

	public static String sendCodeAsSMS(String phoneNum, Map<String, Integer> status) throws Exception {
		String code = getRandomCode(4);
		CloseableHttpClient client = HttpClients.createDefault();
		Map<String, String> params = new HashMap<String, String>();
		CloseableHttpResponse response = null;
		params.put("username", SMS_USERNAME);
		params.put("password", SMS_PASSWORD);
		params.put("mobile", phoneNum);
		params.put("content", MessageFormat.format(SMS_TEXT, code));
		HttpPost method = new HttpPost(SMS_URL);
		if (params != null) {
			List<NameValuePair> paramList = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> param : params.entrySet()) {
				NameValuePair pair = new BasicNameValuePair(param.getKey(), param.getValue());
				paramList.add(pair);
			}
			method.setEntity(new UrlEncodedFormEntity(paramList, "UTF-8"));
		}
		response = client.execute(method);
		HttpEntity entity = response.getEntity();
		if (entity != null) {
			String result = EntityUtils.toString(entity);
			XStream xs = new XStream(new StaxDriver());
			xs.alias("result", Result.class);
			Result object = (Result)xs.fromXML(result);
			response.close();
			status.put(Constants.SMS_RETURNCODE, object.getResultcode());
			if (0 == object.getResultcode()) {
				return code;
			}
		}
		return null;
	}

	public static AddressDTO getDefaultAddress(String jsonList) {
		List<AddressDTO> addressDTOs = JsonParseUtil.parseAddressList(jsonList);
		for (AddressDTO addressDTO : addressDTOs) {
			if (addressDTO.getDefaultAddress() == 1) {
				return addressDTO;
			}
		}
		return null;
	}

	public static String getOrderSn(Long id) {
		if (id == null)
			throw new NullPointerException("id can not be null");

		SimpleDateFormat format = new SimpleDateFormat("yyMMdd");
		String date = format.format(new Date());
		String sn = String.format("%0" + 5 + "d", id);
		return "LTR" + date + sn;
	}

	public static String formatDateToString(String format, Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		return sdf.format(date);
	}

	public static Date formatStringToDate(String format, String dateStr) {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(dateStr);
		} catch (ParseException e) {
			e.printStackTrace();
			date = new Date();
		}
		return date;
	}

}
