import json
import logging
import urllib.request

from ..interfaces.iqueueprocessor import IQueueProcessor

class WeChatQueueProcessor(IQueueProcessor):
    def __init__(self, app_id, app_secret):
        self.app_id = app_id
        self.app_secret = app_secret

    # See: http://admin.wechat.com/wiki/index.php?title=Access_token
    def get_access_token(self):
        url = (
            "https://api.wechat.com/cgi-bin/token"
            "?grant_type=client_credential"
            "&appid=%s"
            "&secret=%s"
        ) % (
            self.app_id,
            self.app_secret
        )

        response = urllib.request.urlopen(url)
        response_body = response.read().decode('utf-8')
        token_info = json.loads(response_body)

        if not 'errcode' in token_info:
            return token_info['access_token']

        logging.error("Error getting WeChat access token: %s", body)
        return None

    # See: http://admin.wechat.com/wiki/index.php?title=Customer_Service_Messages
    def process_message(self, message):
        access_token = self.get_access_token()

        if access_token != None:
            url = "https://api.wechat.com/cgi-bin/message/custom/send?access_token=%s" % access_token
            request_body = {
                'touser': message['sender'],
                'msgtype': 'text',
                'text': {
                    'content': 'Your request has been processed, thank you!'
                }
            }

            response = urllib.request.urlopen(url, json.dumps(request_body).encode('utf-8'))
            response_body = response.read().decode('utf-8')

            if 'errcode' in response_body and response_body['errcode'] == 0:
                logging.error("Error sending Customer Service type message: %s", response_body)
                return True

        return False

@@ -146,16 +146,67 @@
 essor):%0A
+    WECHAT_URL = %22https://api.wechat.com/cgi-bin%22%0A%0A
     def 
@@ -442,38 +442,10 @@
    %22
-https://api.wechat.com/cgi-bin
+%25s
 /tok
@@ -555,16 +555,45 @@
   ) %25 (%0A
+            self.WECHAT_URL,%0A
         
@@ -949,16 +949,25 @@
 n: %25s%22, 
+response_
 body)%0A  
@@ -1211,38 +1211,10 @@
  = %22
-https://api.wechat.com/cgi-bin
+%25s
 /mes
@@ -1248,16 +1248,34 @@
 en=%25s%22 %25
+ (self.WECHAT_URL,
  access_
@@ -1275,24 +1275,25 @@
 access_token
+)
 %0A           
@@ -1678,16 +1678,63 @@
 'utf-8')
+%0A            result = json.loads(response_body)
 %0A%0A      
@@ -1762,36 +1762,22 @@
  res
-ponse_body and response_body
+ult and result
 %5B'er
@@ -1790,16 +1790,62 @@
 %5D == 0:%0A
+                return True%0A            else:%0A
         
@@ -1935,36 +1935,8 @@
 ody)
-%0A                return True
 %0A%0A  

Change Queue Processor module to make it testable and fix a logging bug.