package com.palmnest.application.core.util;

import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.lang3.StringUtils;

import com.turo.pushy.apns.ApnsClient;
import com.turo.pushy.apns.ApnsClientBuilder;
import com.turo.pushy.apns.PushNotificationResponse;
import com.turo.pushy.apns.util.SimpleApnsPushNotification;
import com.turo.pushy.apns.util.TokenUtil;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PushIosMessageUtils {
	
	 private static ApnsClient apnsClient = null;
	 private static final Semaphore semaphore = new Semaphore(10000);
	 public static       String certificatePassword               = PropertiesKit.readPropertiesValue("certificatePassword", "wechat.properties");
	 public static       String newIosMsg               = PropertiesKit.readPropertiesValue("newIosMsg", "wechat.properties");
	 public static       String os               = PropertiesKit.readPropertiesValue("os", "wechat.properties");
	 public static void push(final List<String> deviceTokens, String alertTitle, String alertBody, Map<String, String> map) {
	        if(apnsClient == null) {
	            try{
	                EventLoopGroup eventLoopGroup = new NioEventLoopGroup(4);
	                String certificatePath ="";
	                if("window".equals(os)){
	                	certificatePath ="D:\\test\\floorWindow.p12";//本地地址
	                }else{
	                	certificatePath = PushMessageUtils.class.getClassLoader().getResource("/floorWindow.p12").getPath();//linux目录下获取证书地址
	                }
	                if(StringUtils.isEmpty(certificatePassword)){
	                	certificatePassword = "Huang0910";//此处注意导出的证书密码不能为空因为空密码会报错
	                }
//	                apnsClient = new ApnsClientBuilder().setApnsServer(ApnsClientBuilder.PRODUCTION_APNS_HOST).setClientCredentials(new File(certificatePath), certificatePassword)
//	                        .setConcurrentConnections(4).setEventLoopGroup(eventLoopGroup).build();//正式环境
	              apnsClient = new ApnsClientBuilder().setApnsServer(ApnsClientBuilder.DEVELOPMENT_APNS_HOST).setClientCredentials(new File(certificatePath), certificatePassword)
	              .setConcurrentConnections(4).setEventLoopGroup(eventLoopGroup).build();//测试环境
	            } catch(Exception e) {
	                e.printStackTrace();
	                log.error("新的ios推送异常:"+e.getMessage());
	            }
	        }
	        
	        final CountDownLatch latch = new CountDownLatch(deviceTokens.size());
	        try{
	            final AtomicLong successCnt = new AtomicLong(0);
	            for(String deviceToken : deviceTokens) {
//	                ApnsPayloadBuilder payloadBuilder = new ApnsPayloadBuilder();
	                String sound="tips_addOrder.mp3";
//	                payloadBuilder.setAlertBody("{\"title\":\"" + alertTitle + "\",\"body\":\"" + alertBody + "\",\"mediaFileCode\":\"" + sound + "\",\"tipsNum\":\"" + 123 + "\"}," +
//	                        "\"url\":\"" + "http://www.baidu.com" + "\"}");
//	                payloadBuilder.setAlertTitle(alertTitle);
//	                payloadBuilder.setAlertSubtitle("dfsaf");//副标题
//	                String sound="tips_addOrder.mp3";
	                String json = "{\"tipsNum\":\"123\",\"mediaPushTitle\":\"我是标题哦\",\"code\":\"5001\",\"mediaFileCode\":\"tips_addOrder\",\"aps\":{\"alert\":{\"subtitle\":\"dfsaf\",\"body\":\"我的内容\",\"title\":\"我的标题\"},\"sound\":\"tips_addOrder.mp3\",\"url\":\"http://zhly.superdesk.cn/avicfile/super_wechat/noticeDetail/index.html?type=APP_NIOTICE_AUDIT&id=784\"},\"mediaPushContent\":\"我是内容哦\",\"id\":\"6E6BEE3BBF91766A\",\"mediaFileUrl\":\"https://superdesk.avic-s.com/avicfile/tips/tips_addOrder.mp3\"}";
//	                
//	                if (map != null && !map.isEmpty()) {
//	                    Object[] keys = map.keySet().toArray();
//	                    Object[] vals = map.values().toArray();
//	                    if (keys != null && vals != null && keys.length == vals.length) {
//	                        for (int i = 0; i < map.size(); i++) {
//	                        	payloadBuilder.addCustomProperty(String.valueOf(keys[i]), String.valueOf(vals[i]));
//	                        }
//	                    }
//	                }
//	                payloadBuilder.setSoundFileName(sound);
//	                String payload = payloadBuilder.buildMdmPayload(json);
//	                String payload = payloadBuilder.buildWithDefaultMaximumLength();
//	                LOG.info("payload:"+payload);
	                final String token = TokenUtil.sanitizeTokenString(deviceToken);
	                SimpleApnsPushNotification pushNotification = new SimpleApnsPushNotification(token, "com.ChaoJiQianTai.ZHLY", json);
	                try{
	                    semaphore.acquire();
	                } catch(InterruptedException e) {
	                    e.printStackTrace();
	                }
	                final Future future = apnsClient.sendNotification(pushNotification);
	                future.addListener(new GenericFutureListener() {
	                    @Override
	                    public void operationComplete(Future pushNotificationResponseFuture) throws Exception {
	                        if(future.isSuccess()) {
	                            final PushNotificationResponse response = (PushNotificationResponse)future.getNow();
	                            if(response.isAccepted()) {
	                                successCnt.incrementAndGet();
	                            } else{
	                                Date invalidTime = response.getTokenInvalidationTimestamp();
	                                if(invalidTime != null) {
	                                }
	                            }
	                        } else{
	                        }
	                        latch.countDown();
	                        semaphore.release();
	                    }
	                });
	            }
	        }catch(Exception e){
	        	e.printStackTrace();
	        }
	        
	        try{
	            latch.await(20, TimeUnit.SECONDS);
	        } catch(InterruptedException e) {
	            e.printStackTrace();
	        }
	    }

}
