package cokr.xit.fims.base.web;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;

import cokr.xit.base.docs.xls.CellDef;
import cokr.xit.base.docs.xls.XLSWriter;
import cokr.xit.base.syslog.LogQuery;
import cokr.xit.base.syslog.service.LoggingService;
import cokr.xit.fims.task.TaskRequestMappingHandlerMapping;
import cokr.xit.foundation.data.DataFormat;
import cokr.xit.foundation.data.DataObject;
import cokr.xit.foundation.web.RequestHandlerReader;

@Controller
public class LoggingController extends cokr.xit.base.syslog.web.LoggingController {
	@Resource(name = "loggingService")
	private LoggingService loggingService;

	@Autowired
	private TaskRequestMappingHandlerMapping requestHandlers;

	private RequestHandlerReader requestReader = new RequestHandlerReader();

	@Override
	public ModelAndView getLogs(LogQuery req) {
		if (req.getUserAccounts() != null && req.getUserAccounts().length > 0
				&& req.getUserAccounts()[0] != null) {
			 String[] userAccounts = req.getUserAccounts();
			 for(int i=0; i < userAccounts.length ; i++) {
				 userAccounts[i] = userAccounts[i].toUpperCase();
			 }
			 req.setUserAccounts(userAccounts);
		}

		boolean download = !isEmpty(req.getDownload());
		if (!download)
			setFetchSize(req);
		else
			req.setPageNum(0).setFetchSize(0);

		String
			toDate = req.getToDate(),
			fromDate = req.getFromDate();
		if (isEmpty(toDate)) {
			Date date = new Date();
			toDate = DataFormat.yyyy_mm_dd(date);
			req.setToDate(toDate.replace("-", ""));

			if (isEmpty(fromDate)) {
				fromDate = DataFormat.yyyy_mm_dd(new Date(date.getTime() - 1000L * 60L * 60L * 24L * 30L));
				req.setFromDate(fromDate.replace("-", ""));
			}
		}

		List<DataObject> list = loggingService.getLogs(req);
		if (!list.isEmpty()) {
			Map<String, DataObject> reqs = requestReader.asTree(requestHandlers).getIndex();
			list.forEach(row -> {
				Object obj = row.get("REG_DT");
				row.set("REG_DT", DataFormat.yyyy_mm_dd_hh_mm_ss(obj));

				obj = row.get("URL");
				if (isEmpty(obj)) return;

				DataObject reqInfo = reqs.get(obj);
				row.set("DSCRP", reqInfo != null ? reqInfo.get("name") : "");
			});
		}

		if (!download)
			return setCollectionInfo(
				new ModelAndView("jsonView")
					.addObject("fromDate", fromDate)
					.addObject("toDate", toDate),
				list,
				"syslog"
			);
		else
			return download(list);
	}

	private ModelAndView download(List<DataObject> list) {
		List<CellDef> cellDefs = List.of(
			new CellDef().setLabel("계정").setField("USER_ACNT"),
			new CellDef().setLabel("사용자이름").setField("USER_NM"),
			new CellDef().setLabel("IP 주소").setField("IP_ADDR"),
			new CellDef().setLabel("로그유형").setField("LOG_TYPE_NM"),
			new CellDef().setLabel("접속일시").setField("REG_DT"),
			new CellDef().setLabel("URL").setField("URL"),
			new CellDef().setLabel("설명").setField("DSCRP"),
			new CellDef().setLabel("파일이름").setField("FILE_NM"),
			new CellDef().setLabel("민감정보").setField("PSNL_INFO")
		);
		XLSWriter xlsx = new XLSWriter()
			.worksheet(0)
			.trackWidth(IntStream.range(0, cellDefs.size()).toArray())
			.cell(0, 0)
			.value("시스템 로그 목록").merge(0, cellDefs.size() - 1)
			.cell(2, 0)
			.rowValues(CellDef.header(cellDefs, null))
			.cell(3, 0)
			.values(
				list,
				CellDef.values(cellDefs)
			)
			.autoWidth();

		return new ModelAndView("downloadView")
			.addObject("download",
				xlsx.getDownloadable()
					.setFilename("시스템 로그 목록.xlsx")
			);
	}
}