package com.reyun.controller;

import com.reyun.model.Account;
import com.reyun.model.App;
import com.reyun.repository.AccountRepository;
import com.reyun.repository.AppRepository;
import com.reyun.repository.TranslationRepository;
import com.reyun.security.annotation.CurrentAccount;
import com.reyun.util.Constant;
import com.reyun.util.HttpClientUtil;
import com.reyun.util.MailUtils;
import com.reyun.util.StringUtil;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@Controller
@RequestMapping(value = "/logtool/{appid}")
public class LogController {
	protected static Logger logger = LoggerFactory.getLogger(LogController.class);

	@Autowired
    AppRepository apprepository;
	
	@Autowired
    AccountRepository accountrepository;
	
	@Autowired
    TranslationRepository translationRepository;

	@RequestMapping(method = RequestMethod.GET)
	@ResponseBody
	public List getlogs(HttpServletRequest request, @PathVariable Long appid, @CurrentAccount Account loginAccount) {
		App app = apprepository.findOne(appid);
		Account parent = accountrepository.findOne(app.getAccount());
		Account account = loginAccount;
		List result = null;
		
		try {
			result = getLogs(app.getAppkey());
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		if(result==null) {
			result = new ArrayList();
		}
		return result;
	}
	
	public List getLogs(String appId) throws IOException {
		List<JSONObject> obList = new ArrayList<JSONObject>();
		
		String[] hostArray = Constant.receiverHost.split(",");
		for (String host : hostArray) {
			String url = "http://"+host.trim()+":"+ Constant.receiverPort+"/receive/newlylogs/"+appId;
			try {
				String httpresult = HttpClientUtil.doHttpGetRequest(url, host);
				if (!StringUtil.isEmpty(httpresult)) {
                    try {
                        JSONObject httpresultObject = new JSONObject(httpresult);
                        if (httpresultObject.has("result")) {
                            JSONArray resultArray = httpresultObject.getJSONArray("result");

                            for (int i=0; i<resultArray.length(); i++) {
                                JSONObject ob = resultArray.getJSONObject(i);

                                obList.add(ob);
                            }
                        }
                    } catch (JSONException e) {

                        e.printStackTrace();
                    }
                }
			} catch (Exception e) {
				logger.error("url: {}", url, e);
				try {
					MailUtils.sendSimpleEmail("日志流服务", "日志流服务暂不可用, url: " + url + ", message:" + e.getMessage(), Constant.mlist);
				} catch (Exception e1) {
					logger.error("邮件服务不可用 getLogs()");
				}
				continue;
			}
		}

		Collections.sort(obList, new Comparator<JSONObject>() {

            public int compare(JSONObject arg0, JSONObject arg1) {

                try {
					return (arg1.getString("when")).compareTo((String) arg0.getString("when"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
                return 0;
            }

        });
		List<String> resultList = new ArrayList<String>();
		/*
		if (obList.size() >= 40) {
			for (int i=0; i<40; i++) {
				resultList.add(obList.get(i).toString());
			}
		} else {
			for (int i=0; i<obList.size(); i++) {
				resultList.add(obList.get(i).toString());
			}
		}*/
		for (JSONObject ob : obList) {
			resultList.add(ob.toString());
		}
		return resultList;
	}
	

	
}
