package cn.reghao.tnb.sb.zk.service;

import cn.reghao.tnb.sb.zk.cluster.Node;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

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

/**
 * @author reghao
 * @date 2022-07-26 10:29:22
 */
@Slf4j
@Service
public class ZkService {
    private final static Map<String, String> map = new HashMap<>();
    private final Node node;
    private final RestTemplate restTemplate = new RestTemplate();

    public ZkService(Node node) {
        this.node = node;
    }

    private HttpServletRequest getRequest() {
        return null;
    }

    public void setName(String name) throws Exception {
        HttpServletRequest servletRequest = getRequest();
        String requestFrom = servletRequest.getHeader("request_from");
        if ("leader".equals(requestFrom)) {

        } else if ("follower".equals(requestFrom)) {

        }

        if (node.isLeader()) {
            map.put(name, name + "-" + System.currentTimeMillis());
            node.getFollowers().forEach(follower -> {
                String[] arr = follower.split(":");
                String host = arr[0];
                String port = arr[1];
                String api = String.format("http://%s:%s/api/name", host, port);
                log.info("同步数据到 follower -> {}", api);

                Map<String, String> map = new HashMap<>();
                map.put("name", name);
                restTemplate.postForLocation(api, map);

                HttpHeaders headers = new HttpHeaders();
                headers.add("request_from", "leader");
                HttpEntity<String> entity = new HttpEntity<>(headers);

                ResponseEntity<String> resp = restTemplate.exchange(api, HttpMethod.POST, entity, String.class);
            });
        } else {
            String leader = node.getLeader();
            String[] arr = leader.split(":");
            String host = arr[0];
            String port = arr[1];
            String api = String.format("http://%s:%s/api/name", host, port);
            log.info("转发数据到 leader -> {}", api);

            Map<String, String> map = new HashMap<>();
            map.put("name", name);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.add("request_from", "follower");

            HttpEntity<String> entity = new HttpEntity<>(headers);
            restTemplate.exchange(api, HttpMethod.POST, entity, String.class);
        }
    }

    public String getName() {
        List<String> list = new ArrayList<>(map.values());
        return list.get(0);
    }
}
