package com.inspect.client.util;

import com.alibaba.fastjson.JSONObject;
import com.inspect.client.service.SpringApplicationContext;
import com.inspect.base.core.utils.HttpClientUtils;
import com.inspect.base.core.utils.StringUtils;
import com.inspect.base.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

@Slf4j
public class CallDeviceApi {
   public static final String DEVICE_API_TOKEN = "device_client_api_token";

   public static JSONObject callDevice(String url, String jsonParam) {
         String result = HttpClientUtils.postJson(url, jsonParam, (String) null);

         if(StringUtils.isEmpty(result)) {
            log.info("callDevice Exception: {} ", "Call remote server failed");
            JSONObject resultJson = new JSONObject();
            resultJson.put("code", "200");
            resultJson.put("msg", "Call remote server failed");
            return resultJson;
         }

         JSONObject json = JSONObject.parseObject(result);
         return json;

   }

   public static String getDeviceToken() {
      RedisService redisService = (RedisService)SpringApplicationContext.getBean(RedisService.class);
      String token = (String)redisService.getCacheObject("device_client_api_token");
      if(StringUtils.isNotBlank(token)) {
         return token;
      } else {
         token = getDeviceTokenFromDevice();
         redisService.setCacheObject("device_client_api_token", token, Long.valueOf(100L), TimeUnit.DAYS);
         return token;
      }
   }

   public static String getDeviceTokenFromDevice() {
      String post = HttpClientUtils.post("");
      JSONObject result = JSONObject.parseObject(post);
      String token = result.getString("token");
      return token;
   }
}
