import random
import threading

import os
from sqlalchemy.sql.expression import and_, select
from sqlalchemy.sql.functions import func

from gengine.app.model import t_subject_device, t_subject_messages
from gengine.base.model import update_connection
from gengine.base.settings import get_settings
from gengine.base.util import lstrip_word
from gengine.metadata import DBSession

threadlocal = threading.local()

import logging
log = logging.getLogger(__name__)

try:
    from apns import APNs, Payload
except ImportError as e:
    log.info("tapns3 not installed")

try:
    from gcm import GCM
except ImportError as e:
    log.info("python-gcm not installed")


def get_prod_apns():
    """
    http://stackoverflow.com/questions/1762555/creating-pem-file-for-apns

    Step 1: Create Certificate .pem from Certificate .p12
    Command: openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns-dev-cert.p12

    Step 2: Create Key .pem from Key .p12
    Command : openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns-dev-key.p12

    Step 3: If you want to remove pass phrase asked in second step
    Command : openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem

    """
    if not hasattr(threadlocal, "prod_apns"):