package com.iamberry.app.international.util;

import com.iamberry.app.international.controller.BaseController;
import com.iamberry.app.tool.dto.TuyaHistoryListDTO;
import com.iamberry.app.tool.dto.TuyaHistoryResultDTO;
import com.iamberry.app.tool.util.TuyaConnector;
import com.iamberry.zk.ZookeeperQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Lazy(false)
@Component("tuyaHistoryConnector")
@RequestMapping("/")
public class TuyaHistoryConnector extends BaseController {

	// Is server restart or crashed?
	private static boolean isRestart;
	private long nextStartTime;
	private final static int LIMIT = 100;
	List<TuyaHistoryListDTO> tmpList = new ArrayList<>();
	private Logger logger = LoggerFactory.getLogger(TuyaHistoryConnector.class);

	/*static {
		isRestart = true;
		ZookeeperQueue.rootElement();
	}*/

	// pull data each 5 minutes
	@Scheduled(fixedDelay = 1000)
	private void startPullHistoryData() {
logger.info("start pull history...");
		long currentime = System.currentTimeMillis() / 1000 * 1000;
		if (isRestart == true) {
			isRestart = false;
			// add 1000 to avoid get same last data again, some may lost
			nextStartTime = milkService.getLastRecordDate().getTime() + 1000;
		}
		tmpList.clear();
		connectorHandler(nextStartTime, currentime, "0");
		nextStartTime = currentime;
	}

	private void connectorHandler(long startTime, long endTime, String offset) {
		try {
			TuyaHistoryResultDTO rawData = TuyaConnector.TuyaHistoryConnect(startTime, endTime, offset, LIMIT);
			if (rawData != null && rawData.getList() != null) {
				logger.info("rawData-size:"+rawData.getList().size());
				if (rawData.getList().isEmpty()) {
					return;
				}
				if (rawData.getNextOffset() == null) {
					tmpList.addAll(rawData.getList());
					tmpList.sort((TuyaHistoryListDTO o1, TuyaHistoryListDTO o2) -> o1.getTime().compareTo(o2.getTime()));
					for (TuyaHistoryListDTO oneRecord : tmpList) {
						// 根据机器ID 获取对应的用户id
						String devId = oneRecord.getDevId();
						Long userId = machineService.selectUserIDByDevId(devId);
						logger.info("add macine reader : "+userId + ",devID：" + devId);
						milkService.addRecordData(oneRecord.getDevId(), oneRecord.getValue(), oneRecord.getTime(), userId);
					}
				} else {
					logger.info("get data end!");
					tmpList.addAll(rawData.getList());
					connectorHandler(startTime, endTime, rawData.getNextOffset());
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
