package com.friday.custody.api.feignconfig;


import com.friday.custody.api.util.HTSCSignGenerator;
import feign.Logger;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.http.entity.ContentType;
import org.springframework.context.annotation.Bean;

import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author 021790
 */
public class HtscFeignConfiguration {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }


    @Bean
    public RequestInterceptor requestInterceptor() {
        return requestTemplate -> {
            HtscHeaders headers= generateParam(requestTemplate);
            requestTemplate.header("Timestamp", headers.getTimestamp());
            requestTemplate.header("Sign", headers.getSign());
            requestTemplate.header("Accept", ContentType.APPLICATION_JSON.getMimeType());
        };
    }


    private HtscHeaders generateParam(RequestTemplate requestTemplate){
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "Z";
        String url = requestTemplate.url();
        String rawUrl = url.substring(0,url.indexOf("?"));

        Map<String, Collection<String>> queries = requestTemplate.queries();
        Map<String,String> paramsMap = new LinkedHashMap<>();
        queries.forEach((key,queryTemplate)->{
            String v = queryTemplate.stream().findAny().get();
            paramsMap.put(key,v);
        });

       String appSecret= queryAppSecret(paramsMap.get("appId"));
       paramsMap.put("timestamp",timestamp);
       paramsMap.put("url",rawUrl);
        String sign = HTSCSignGenerator.genSign(appSecret, paramsMap);

        return  new HtscHeaders(timestamp,sign);
    }

    private String queryAppSecret(String appId){
        //todo getAppSecret from database or cache
       String appSecret = "XacPXl3TqhYDRSvN9wgGTMX+WC4H4n+6DA5IMYrBw/I=";
   //     String appSecret = "8jmCOQDmlAmGmQ5t4MzYyfd/2sY0hBjUn+h+Oq0w5zM=";
        //id=567
        if ("567".equals(appId)){
            return "yPTnDDSt/o73D1S7mb4E6IaN5qZKTF2L4EPjBzy9eHc=";
        }
        return appSecret;
    }

    @Getter
    @Setter
    @AllArgsConstructor
    private class HtscHeaders{
        private String timestamp;
        private String sign;
    }

}


