package com.uas.search.controller;

import com.uas.search.annotation.NotEmpty;
import com.uas.search.constant.model.SPage;
import com.uas.search.jms.JmsListener;
import com.uas.search.jms.LuceneMessage;
import com.uas.search.jms.LuceneMessageDao;
import com.uas.search.jms.LuceneMessageService;
import com.uas.search.service.IndexService;
import com.uas.search.support.DownloadHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import com.uas.search.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

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

    @Autowired
    private LuceneMessageDao luceneMessageDao;

    @Autowired
    private IndexService indexService;

    @Autowired
    private LuceneMessageService luceneMessageService;

    @Autowired
    private JmsListener jmsListener;

    @RequestMapping("/create")
    @ResponseBody
    public String initIndexes(String tableNames, HttpServletRequest request) {
        return String.format("Indexes created success in %.2fs",
                indexService.createIndexes(toList(tableNames), true) / 1000.0);
    }

    /**
     * 根据逗号进行分隔，将字符串转为 List
     *
     * @param input 输入的字符串
     * @return 转为的 List
     */
    private List<String> toList(String input) {
        List<String> list = new ArrayList<>();
        if (!StringUtils.isEmpty(input)) {
            String[] strs = input.split(",");
            for (String str : strs) {
                list.add(str.toLowerCase());
            }
        }
        return list;
    }

    @RequestMapping("/multiDownloadComponent")
    @ResponseBody
    public String multiDownloadComponent(Integer threads, Integer startFileIndex, Integer endFileIndex, String validateResult, HttpServletRequest request) {
        long start = System.currentTimeMillis();
        String message= "Downloaded: "+ indexService.multiDownloadComponent(threads, startFileIndex, endFileIndex,
                StringUtils.isEmpty(validateResult) ? DownloadHelper.ValidateResult.CURRENT : DownloadHelper.ValidateResult.valueOf(validateResult.toUpperCase()));
        message += String.format(", Time: %.2fs", (System.currentTimeMillis()-start)/1000.0);
        return message;
    }

    @RequestMapping("/multiDownloadGoods")
    @ResponseBody
    public String multiDownloadGoods(Integer threads, Integer startFileIndex, Integer endFileIndex, String validateResult, HttpServletRequest request) {
        long start = System.currentTimeMillis();
        String message= "Downloaded: "+ indexService.multiDownloadGoods(threads, startFileIndex, endFileIndex,
                StringUtils.isEmpty(validateResult) ? DownloadHelper.ValidateResult.CURRENT : DownloadHelper.ValidateResult.valueOf(validateResult.toUpperCase()));
        message += String.format(", Time: %.2fs", (System.currentTimeMillis()-start)/1000.0);
        return message;
    }

    @RequestMapping("/listen/start")
    @ResponseBody
    public String startListen(Long interval, HttpServletRequest request) {
        jmsListener.start(interval);
        return "开启成功";
    }

    @RequestMapping("/listen/stop")
    @ResponseBody
    public String stopListen(HttpServletRequest request) {
        jmsListener.stop();
        return "关闭成功";
    }

    @RequestMapping("/listen/restart")
    @ResponseBody
    public String restartListen(Long interval, HttpServletRequest request) {
        if (jmsListener.isRunning()) {
            jmsListener.stop();
        }
        jmsListener.start(interval);
        return "重启成功";
    }

    @RequestMapping("/listen/details")
    @ResponseBody
    public SPage<LuceneMessage> listenDetails(Integer page, Integer size, HttpServletRequest request) {
        return luceneMessageService.findAll(page, size);
    }

    @RequestMapping("/maintain")
    @ResponseBody
    public String maintainIndexes(@NotEmpty("tableName") String tableName, @NotEmpty("dataId") Long dataId, @NotEmpty("methodType") String methodType, String data,
                                  HttpServletRequest request) {
        return "已维护：" + indexService.maintainIndexes(tableName.toLowerCase(), dataId, methodType, data);
    }

    @RequestMapping("/dequeue")
    @ResponseBody
    public boolean dequeueLuceneQueueMessage(Long id, HttpServletRequest request) {
        luceneMessageDao.dequeueLuceneMessage(id);
        return true;
    }

    @RequestMapping("/updateByNewWords")
    @ResponseBody
    public Map<String, List<Object>> updateIndexByNewWords(String newWords, HttpServletRequest request) {
        return indexService.updateIndexByNewWords(toList(newWords));
    }
}
