package mobvista.dmp.datasource.baichuan;

import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaBaichuanAsoQueryRequest;
import com.taobao.api.response.AlibabaBaichuanAsoQueryResponse;
import mobvista.dmp.util.PropertyUtil;
import org.apache.commons.lang.StringUtils;

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

/**
 * @package: mobvista.dmp.datasource.baichuan
 * @author: wangjf
 * @date: 2019-08-26
 * @time: 15:44
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */

public class BaiChuanServer {
    /**
     * fix java.util.ConcurrentModificationException
     * CopyOnWriteArrayList也是一个线程安全的ArrayList，其实现原理在于，每次add,remove等所有的操作都是重新创建一个新的数组，再把引用指向新的数组。
     * new CopyOnWriteArrayList<>() 适用于读操作频繁
     * Collections.synchronizedList(new ArrayList<>()) 适用于写操作频繁
     */

    /**
     * @param appId 应用ID，1-tmail,2-taobao
     * @param appOs 设备ID类型，1-android,2-ios
     * @return
     * @throws ApiException
     */
    public static AlibabaBaichuanAsoQueryResponse request(String appId, String appOs, Set<String> deviceSet) throws ApiException {
        String serverUrl = PropertyUtil.getProperty("config.properties", "http.server.url");
        //  可替换为您的沙箱环境应用的AppKey
        String appKey = PropertyUtil.getProperty("config.properties", "http.server.appKey");
        //  可替换为您的沙箱环境应用的AppSecret
        String appSecret = PropertyUtil.getProperty("config.properties", "http.server.appSecret");
        TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
        AlibabaBaichuanAsoQueryRequest req = new AlibabaBaichuanAsoQueryRequest();
        /**
         *  1-tmail,2-taobao
         */
        req.setAppId(appId);
        /**
         *  1-android,2-ios
         */
        req.setAppOs(Long.parseLong(appOs));
        //  the array size of deviceInfoList must be less than 20.
        List<AlibabaBaichuanAsoQueryRequest.ASODeviceInfoDO> list = new ArrayList<>();
        for (String deviceId : deviceSet) {
            AlibabaBaichuanAsoQueryRequest.ASODeviceInfoDO obj = new AlibabaBaichuanAsoQueryRequest.ASODeviceInfoDO();
            list.add(obj);
            if (StringUtils.isNotBlank(deviceId)) {
                if (Integer.parseInt(appOs) == 1) {
                    obj.setImei(deviceId);
                } else {
                    obj.setIdfa(deviceId.toUpperCase());
                }
            }
        }
        req.setDeviceInfoList(list);
        AlibabaBaichuanAsoQueryResponse rsp = client.execute(req);
        return rsp;
    }
}
