package com.goafanti.message;

import java.net.URI;
import java.util.List;

import io.netty.handler.codec.http.HttpMethod;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.goafanti.common.utils.LoggerUtils;
import com.goafanti.message.bo.MessageAdapter;
import com.goafanti.message.bo.MessageBo;
import com.goafanti.message.push.model.Platform;
import com.goafanti.message.push.model.PushPayload;
import com.goafanti.message.push.model.audience.Audience;
import com.goafanti.message.push.model.audience.AudienceTarget;
import com.goafanti.message.push.model.notification.AndroidNotification;
import com.goafanti.message.push.model.notification.IosNotification;
import com.goafanti.message.push.model.notification.Notification;
import com.goafanti.message.queue.MessageRedisQueue;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NettyHttpClient;
import cn.jiguang.common.resp.ResponseWrapper;

/**
 * 极光推送
 * @author Administrator
 *
 */
public class JGMessageHelper implements InitializingBean, DisposableBean{
	@Value(value = "${jiguang.appKey}")
	private String appKey; 
	@Value(value = "${jiguang.masterSecret}")
	private String masterSecret;
	@Value(value = "${jiguang.pushUrl}")
	private String pushUrl;
	@Autowired
	private MessageRedisQueue jedisQueue;
	private static final int UN_AUTH	= 401;//未验证
	private static final int NOT_SUITABLE = 405;//不支持该请求方法
	private static final int EXCEED_THE_LIMIT = 429;//超过频率限制
	private static final Logger logger = LoggerFactory.getLogger(JGMessageHelper.class);
	private static final int MAX_TRYCOUNT = 3;
	private static final String MESSAGE_ID = "message_id";//消息ID
	private static final String RESOURCE_ID =  "resource_id";//资源ID
	private static final String RESOURCE_TYPE = "resource_type";//资源类型
	public void send(MessageAdapter messageAdapter){
		ClientConfig clientConfig = ClientConfig.getInstance();
	   String host = (String) clientConfig.get(ClientConfig.PUSH_HOST_NAME);
        final NettyHttpClient client = new NettyHttpClient(ServiceHelper.getBasicAuthorization(appKey, masterSecret), null, clientConfig);
        try {
            URI uri = new URI(host + clientConfig.get(ClientConfig.PUSH_PATH));
            PushPayload payload = messageAdapter.getPushPayload();
            logger.info(payload.toJSON().toString());
            client.sendRequest(HttpMethod.POST, payload.toString(), uri, new NettyHttpClient.BaseCallback() {
                @Override
                public void onSucceed(ResponseWrapper responseWrapper) {
                    logger.info("Got result Content: " + responseWrapper.responseContent + "Code:" +responseWrapper.responseCode);
                    if(responseWrapper.responseCode == UN_AUTH){
                    	LoggerUtils.debug(logger, "Request Not Authorized");
                    }else if(responseWrapper.responseCode == NOT_SUITABLE){
                    	LoggerUtils.debug(logger, "Request Not Allow");
                    }else if(responseWrapper.responseCode == EXCEED_THE_LIMIT){
                    	LoggerUtils.debug(logger, "Request Too Frequent");
                    }
                }
            });
        } catch (Exception e) {
        	sendLater(messageAdapter);
            e.printStackTrace();
        }finally {
        	client.close();   
		}
	}

	public void sendLater(MessageAdapter messageAdapter) {
		if(messageAdapter.getTryCount() < MAX_TRYCOUNT) 
			jedisQueue.pushFromTail(messageAdapter.tryCount(messageAdapter.getTryCount()+1));
	}

	public void sendSystemMessage(MessageBo mb){
		MessageAdapter ma = new MessageAdapter();
		if(StringUtils.isNotBlank(mb.getRegistrationId())){
			ma.pushPayload(PushPayload.newBuilder()
					.setPlatform(Platform.android_ios())
					.setAudience(Audience.newBuilder()
							.addAudienceTarget(
									AudienceTarget.registrationId(mb.getRegistrationId()))
							.build())
					.setNotification(Notification.newBuilder()
			        		.setAlert(mb.getMessageTitle())
			        		.addPlatformNotification(AndroidNotification.newBuilder()
			        				.addExtra(MESSAGE_ID, mb.getMessageId())
			        				.addExtra(RESOURCE_ID, mb.getResourceId() == null ? "" : mb.getResourceId())
			        				.addExtra(RESOURCE_TYPE, mb.getResourceType()== null ? "": mb.getResourceType())
			        				.build())
			        		.addPlatformNotification(IosNotification.newBuilder()
			        				.incrBadge(1)
			        				.setContentAvailable(true)
			        				.addExtra(MESSAGE_ID, mb.getMessageId())
			        				.addExtra(RESOURCE_ID, mb.getResourceId() == null ? "" : mb.getResourceId())
			        				.addExtra(RESOURCE_TYPE, mb.getResourceType()== null ? "": mb.getResourceType())
			        				.build())
			        		.build())
					.build());
			send(ma);
		}
	}
	
	public void sendSystemMessage(MessageBo... mb){
		for(MessageBo bo : mb){
			sendSystemMessage(bo);
		}
	}
	
	public void sendSystemMessage(List<MessageBo> mb){
		for(MessageBo bo : mb){
			sendSystemMessage(bo);
		}
	}
	
	@Override
	public void destroy() throws Exception {
		LoggerUtils.debug(logger, "消息系统关闭");
		
	}
	@Override
	public void afterPropertiesSet() throws Exception {
		
	}

	public static void main(String[] args) {
		JGMessageHelper jgMessageHelper = new JGMessageHelper();
		MessageAdapter ma = new MessageAdapter().pushPayload( 
				PushPayload.newBuilder()
		.setPlatform(Platform.android_ios())
		.setAudience(Audience.newBuilder()
				.addAudienceTarget(
						AudienceTarget.registrationId("101d8559094270e0d78"))
				.build())
		.setNotification(Notification.newBuilder()
        		.setAlert("消息标题")
        		.addPlatformNotification(AndroidNotification.newBuilder()
        				.addExtra(MESSAGE_ID,"消息id")
        				.addExtra(RESOURCE_ID,"资源id")
        				.addExtra(RESOURCE_TYPE, "资源类型")
        				.build())
        		.addPlatformNotification(IosNotification.newBuilder()
        				.incrBadge(1)
        				.setContentAvailable(true)
        				.addExtra(MESSAGE_ID,"消息id")
        				.addExtra(RESOURCE_ID,"资源id")
        				.addExtra(RESOURCE_TYPE, "资源类型")
        				.build())
        		.build())
		.build());
		jgMessageHelper.send(ma);
	}
}
