# Copyright (c) 2010 ActiveState Software Inc. All rights reserved.
"""
    pypm.util.licensing
    ~~~~~~~~~~~~~~~~~~~
 
    ActiveState license-related functions
"""

import os
from os import path as P
import sys
import logging

LOG = logging.getLogger(__name__)

# Business Edition landing page at activestate.com
BE_HOME_PAGE = 'www.activestate.com/business-edition'


def get_license_location():
    """Return the ActiveState license file location"""
    try:
        return os.environ['ACTIVESTATE_LICENSE']
    except KeyError:
        try:
            asdir = os.environ['ACTIVESTATE_HOME']
        except KeyError:
            if sys.platform.startswith('win'):
                from appdirs import _get_win_folder
                appdata = _get_win_folder("CSIDL_APPDATA")
                asdir = P.join(appdata, 'ActiveState')
            elif sys.platform.startswith('darwin'):
                asdir = P.expanduser('~/Library/Application Support/ActiveState')
            else:
               asdir = P.expanduser('~/.ActiveState')
        return P.join(asdir, 'ActiveState.lic')
        
        
def get_be_license_auth():
    """Return the serial no and API password for the user's BE license
    
    Return `None` if none is available/installed.
    """
    licpath = get_license_location()
    if P.exists(licpath):
        for line in open(licpath):
            if 'ActivePython BE' in line:
                parts = line.split('|')
                fields = {}
                for part in parts:
                    part = part.strip()
                    if '#' in part:
                        key, value = part.split('#')
                        fields[key] = value
                if 'APIPassword' in fields and 'SerialNo' in fields:
                    return fields['SerialNo'], fields['APIPassword']
        LOG.debug('Cannot find a BE license in %s', licpath)
    else:
        LOG.debug('No ActiveState license found on this machine')


def user_has_be_license():
    """Return True if the user has BE license installed
    
    Their BE license may or may not be valid though. This function only
    cares for the *existence* (not *validation*) of the license. Because
    validation happens on the server side and hence we wouldn't know.
    """
    return get_be_license_auth() is not None
