
import settings
import uuid
import keystoneclient
from keystoneclient.v3 import client
from datetime import datetime
from neutronclient.v2_0 import client as neutron_client
import logging as log
from flask import current_app
import time


KEYSTONE_PUBLIC_V2_ENDPOINT = settings.KEYSTONE_PUBLIC_ENDPOINT
KEYSTONE_PUBLIC_V2_ENDPOINT = KEYSTONE_PUBLIC_V2_ENDPOINT.replace('/v3','/v2.0')

def write_log(data):
    f=open("/tmp/custom.log","a")
    f.write(data)
    f.close()	
		

def get_client():
    """
    """
    keystone = client.Client(token=settings.KEYSTONE_ADMIN_TOKEN, 
                    endpoint=settings.KEYSTONE_ADMIN_ENDPOINT)
    return keystone

def get_neutron_client(uname,pwd,tenantname):
    """                 
    """                 
    try:
        neutron = neutron_client.Client(username=uname,password=pwd,auth_url=KEYSTONE_PUBLIC_V2_ENDPOINT,tenant_name=tenantname)
        neutron.format= 'json'
    except Exception as e:
        current_app.logger.exception("Exception in neutron client")
        current_app.logger.exception(e)
    #neutron = neutron_client.Client(token=settings.KEYSTONE_ADMIN_TOKEN,auth_url=settings.KEYSTONE_PUBLIC_V2_ENDPOINT,tenant_name=tenantname)
    return neutron

def _create_user(name, domain=None, project=None, password=None,
                        email=None, description=None, enabled=None,
                        default_project=None, keystone=None, 
                        **kwargs):
    """
    """
    if not keystone:
        keystone = get_client()
    user = keystone.users.create(name, domain=None, project=None, password=password, 
            email=email, description=None, enabled=enabled, default_project=None,
            **kwargs)
    return user


def create_user(name, password, email=None, description=None, enabled=False, **kwargs):
    """
    """
    project = None
    user = None
    network = None
    role_granted = False
    neutron = None 
    keystone = get_client()
    _user = get_user_by_name(name)
    if _user:
        raise keystoneclient.apiclient.exceptions.Conflict("User already exist")
    try:
        domain = get_default_domain(keystone) 
        tenant_name = name + '-' + datetime.now().strftime('%Y%m%d%H%M%S')
        project = create_project(domain, tenant_name , keystone)
        role = get_default_role(keystone)
        ##SM:domain is optional
        user = _create_user(name, domain=domain, project=project, password=password, 
            email=email, enabled=enabled, keystone=keystone, **kwargs)
        ##SM:Specify either a domain or project, not both
        keystone.roles.grant(role, user=user, domain=None, project=project)
        role_granted = True
        user = keystone.users.update(user=user.id,enabled=True)
        time.sleep(5)        
        try:
            neutron = get_neutron_client(name,password,tenant_name)
        except Exception as e:
            log.exception("Exception while initializing neutron client")
            current_app.logger.exception(e)
        try:
            if neutron:
                network = create_network(neutron,domain.name)
        except Exception as e:
            current_app.logger.exception(e)