package com.chenyang.nse.bussiness.service.webApi.impl;

import com.chenyang.nse.bussiness.config.WebApiConfig;
import com.chenyang.nse.bussiness.entity.webApi.ApiCode;
import com.chenyang.nse.bussiness.entity.webApi.DataParams;
import com.chenyang.nse.bussiness.entity.webApi.DataParamsList;
import com.chenyang.nse.bussiness.entity.webApi.Msg;
import com.chenyang.nse.bussiness.service.webApi.WebApiService;
import com.chenyang.nse.bussiness.service.webApi.business.Scheduler;
import com.chenyang.nse.bussiness.service.webApi.business.SecretKeyCache;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class WebApiServiceImpl implements WebApiService {
   private static final Logger LOGGER = LoggerFactory.getLogger(WebApiServiceImpl.class);
   @Autowired
   private WebApiConfig config;

   public Msg enc(DataParamsList dataParamsList) {
      Msg msg = this.perform(0, dataParamsList);
      return msg;
   }

   public Msg dec(DataParamsList dataParamsList) {
      return this.perform(1, dataParamsList);
   }

   private Msg perform(int type, DataParamsList dataParamsList) {
      if (type != 0 && type != 1) {
         return Msg.error(ApiCode.other, "不支持的处理方法");
      } else {
         try {
            if (dataParamsList != null && dataParamsList.getConfigs() != null && dataParamsList.getConfigs().size() != 0) {
               int total = 0;
               List<String> unconfigIds = new ArrayList();

               for(DataParams config : dataParamsList.getConfigs()) {
                  total += config.getValues() == null ? 0 : config.getValues().length;
                  String id = config.getId();
                  String key = SecretKeyCache.instance().getKey(id);
                  if (key == null) {
                     unconfigIds.add(id);
                  }
               }

               if (unconfigIds.size() > 0) {
                  return Msg.error(ApiCode.unconfig, String.join(",", unconfigIds));
               } else if (total > this.config.getMaxValueSize()) {
                  return Msg.error(ApiCode.dataOverflow, total + "");
               } else {
                  Scheduler scheduler = new Scheduler(dataParamsList);
                  return scheduler.perform(type, total);
               }
            } else {
               return Msg.succed(dataParamsList);
            }
         } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return Msg.error(ApiCode.other, e.getMessage());
         }
      }
   }
}
