package com.uas.search.console.b2b.controller;

import com.uas.search.b2b.model.SPage;
import com.uas.search.b2b.service.SearchService.Table_name;
import com.uas.search.console.b2b.jms.AQListener;
import com.uas.search.console.b2b.jms.LuceneQueueMessage;
import com.uas.search.console.b2b.service.IndexService;
import com.uas.search.console.b2b.support.DownloadHelper;
import com.uas.search.console.b2b.util.SearchConstants.DataSourceQualifier;
import com.uas.search.util.StringUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

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

/**
 * 索引创建相关请求
 *
 * @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 createIndexs(String tableNames, Boolean fromFiles, Boolean ifStartListener) {
		List<Table_name> tableNameList = getTableNames(tableNames);
		return String.format("Indexes created success in %.2fs",
				indexService.createIndexes(tableNameList, fromFiles, ifStartListener) / 1000.0);
	}

    @RequestMapping("/downloadData")
    @ResponseBody
    public String downloadData(String tableNames) {
        List<Table_name> tableNameList = getTableNames(tableNames);
        return "Data downloaded success in " + indexService.downloadData(tableNameList) + " ms.";
    }

    @RequestMapping("/downloadData/{tableName}")
    @ResponseBody
    public String downloadData(@PathVariable String tableName, Integer startFileIndex) {
        return "Data downloaded success in " + indexService.downloadData(Table_name.valueOf(tableName.toUpperCase()), startFileIndex)
                + " ms.";
    }

    @RequestMapping("/multiDownloadData")
    @ResponseBody
    public String multiDownloadData(String tableNames, Integer threads, String validateResult) {
        long start = System.currentTimeMillis();
        String message= "Downloaded: "+ indexService.multiDownloadData(getTableNames(tableNames), threads, parseValidateResult(validateResult));
        message += String.format(", Time: %.2fs", (System.currentTimeMillis()-start)/1000.0);
        return message;
    }

    @RequestMapping("/multiDownloadData/{tableName}")
    @ResponseBody
    public String multiDownloadData(@PathVariable String tableName, Integer threads, Integer startFileIndex, Integer endFileIndex, String validateResult) {
        long start = System.currentTimeMillis();
        String message= "Downloaded: "+ indexService.multiDownloadData(Table_name.valueOf(tableName.toUpperCase()),
                threads, startFileIndex, endFileIndex, parseValidateResult(validateResult));
        message += String.format(", Time: %.2fs", (System.currentTimeMillis()-start)/1000.0);
        return message;
    }

    private DownloadHelper.ValidateResult parseValidateResult(String validateResult){
        return StringUtils.isEmpty(validateResult) ? DownloadHelper.ValidateResult.CURRENT : DownloadHelper.ValidateResult.valueOf(validateResult.toUpperCase());
    }

    private List<Table_name> getTableNames(String tableNames){
		List<Table_name> tableNameList = null;
		if (!StringUtils.isEmpty(tableNames)) {
			String[] strs = tableNames.split(",");
			tableNameList = new ArrayList<>();
			for (String str : strs) {
				tableNameList.add(Table_name.valueOf(str.toUpperCase()));
			}
		}
		return tableNameList;
	}

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

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

	@RequestMapping("/listen/isRunning")
	@ResponseBody
	public boolean isRunning(String dataSourceQualifier) {
		return aqListener.isRunning(DataSourceQualifier.checkDataSourceType(dataSourceQualifier));
	}

	@RequestMapping("/listen/restart")
	@ResponseBody
	public String restart(String dataSourceQualifiers, Long waitInterval) {
		HashSet<DataSourceQualifier> qualifiers = getDataSourceQualifiers(dataSourceQualifiers);
		aqListener.stop(qualifiers);
		return aqListener.start(qualifiers, waitInterval);
	}

	private HashSet<DataSourceQualifier> getDataSourceQualifiers(String dataSourceQualifiers) {
		if (StringUtils.isEmpty(dataSourceQualifiers)) {
			return null;
		}
		String[] strs = dataSourceQualifiers.split(",");
		HashSet<DataSourceQualifier> qualifiers = new HashSet<>();
		for (String str : strs) {
			qualifiers.add(DataSourceQualifier.checkDataSourceType(str));
		}
		return qualifiers;
	}

	@RequestMapping("/listen/details")
	@ResponseBody
	public SPage<LuceneQueueMessage> listenDetails(String dataSourceQualifier, Integer page, Integer size,
			String searchContent) {
		DataSourceQualifier qualifier = null;
		if (dataSourceQualifier != null) {
			qualifier = DataSourceQualifier.checkDataSourceType(dataSourceQualifier);
		}
		return indexService.getListenDetails(qualifier, page, size, searchContent);
	}

	@RequestMapping("/maintain")
	@ResponseBody
	public String maintainIndexes(@RequestParam String tableName, String ids, String data,
			@RequestParam String method) {
		if (!StringUtils.isEmpty(ids)) {
			return "已维护：" + indexService.maintainIndexesByIds(tableName, ids, method);
		} else {
			return "已维护：" + indexService.maintainIndexesByData(tableName, data, method);
		}
	}

	@RequestMapping("/dequeue")
	@ResponseBody
	public boolean dequeueLuceneQueueMessage(String dataSourceQualifier, String messageId) {
		DataSourceQualifier qualifier = null;
		if (dataSourceQualifier != null) {
			qualifier = DataSourceQualifier.checkDataSourceType(dataSourceQualifier);
		}
		return indexService.dequeueLuceneQueueMessage(qualifier, messageId);
	}
}
