package com.uas.search.console.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.uas.search.console.jms.AQListener;
import com.uas.search.console.model.LuceneQueueMessage;
import com.uas.search.console.service.IndexService;
import com.uas.search.model.SPage;

/**
 * 索引创建相关请求
 * 
 * @author sunyj
 * @since 2016年8月5日 上午11:42:54
 */
@Controller
@RequestMapping("/index")
public class IndexController {

	@Autowired
	private IndexService indexService;

	@Autowired
	private AQListener aqListener;

	@RequestMapping("/create")
	@ResponseBody
	public String initIndexes(String tableNames) {
		List<String> tableNameList = new ArrayList<>();
		if (!StringUtils.isEmpty(tableNames)) {
			String[] strs = tableNames.split(",");
			for (String str : strs) {
				tableNameList.add(str.toLowerCase());
			}
		}
		return String.format("Indexes created success in %.2fs",
				indexService.createIndexes(tableNameList, true) / 1000.0);
	}

	@RequestMapping("/downloadComponentData")
	@ResponseBody
	public String downloadComponentDataFromDatabase(Integer startFileIndex) {
		return "Data downloaded success in " + indexService.downloadComponentDataFromDatabase(startFileIndex) + " ms.";
	}

	@RequestMapping("/listen/start")
	@ResponseBody
	public String startListen(Long waitInterval) {
		return aqListener.start(waitInterval);
	}

	@RequestMapping("/listen/stop")
	@ResponseBody
	public String stopListen() {
		return aqListener.stop();
	}

	@RequestMapping("/listen/restart")
	@ResponseBody
	public String restartListen(Long waitInterval) {
		if (aqListener.isRunning()) {
			aqListener.stop();
		}
		return aqListener.start(waitInterval);
	}

	@RequestMapping("/listen/details")
	@ResponseBody
	public SPage<LuceneQueueMessage> listenDetails(Integer page, Integer size, String searchContent) {
		return indexService.getListenDetails(page, size, searchContent);
	}

	@RequestMapping("/maintain")
	@ResponseBody
	public String maintainIndexes(@RequestParam(required = true) String tableName,
			@RequestParam(required = true) String ids, @RequestParam(required = true) String method) {
		return "已维护：" + indexService.maintainIndexes(tableName, ids, method);
	}

	@RequestMapping("/dequeue")
	@ResponseBody
	public boolean dequeueLuceneQueueMessage(String messageId) {
		return indexService.dequeueLuceneQueueMessage(messageId);
	}
}
