from __future__ import unicode_literals
from django.conf import settings
from random import randint
from jinja2 import Environment, PackageLoader, select_autoescape
from api.utils.docker_api import (
    execute_command,
    run_container,
    copy_in
)
from api.utils.command import execute
import os
import socket
import time
import unicodedata
import stringcase
import tarfile

'''
'''
def normalize_name(name = None):
    if not name:
        return name
    
    try:
        name = unicodedata.normalize('NFKD', name)
        name = name.encode('ASCII', 'ignore') 
    except TypeError:
        pass

    name = stringcase.trimcase(name)
    name = stringcase.lowercase(name)
    name = stringcase.snakecase(name)

    return name

'''
'''
def randomize_port():
    ports = settings.ODOO_PORTS_RANGE
    port = 0

    while not check_port(port):
        time.sleep(1)
        port = randint(ports[0], ports[1])

    return port
    
'''
'''
def check_port(port=0):
    if port == 0:
        return False

    ok = False
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    try:
        s.bind((settings.DOCKER_NETWORK, port))
        ok = True
    except socket.error:
        ok = False
    
    s.close()
    return ok

'''
'''
def check_name(name=None):
    if not name:
        return False

    full_path = os.path.join(settings.ODOO_ROOT_PATH, name)
    return os.path.exists(full_path)

'''
'''
def create_folders(name=None):
    if not name:
        return False

    folders = settings.ODOO_DEFAULT_FOLDERS
    for folder in folders:
        full_path = os.path.join(settings.ODOO_ROOT_PATH, name, folder.strip())
        os.makedirs(full_path)
        time.sleep(1)

    return True

'''
'''
def apply_permissions(name=None):
    if not name:
        return False
    
    full_path = os.path.join(settings.ODOO_ROOT_PATH, name)
    execute(['chmod', '-Rf', '777', full_path])

    return True

'''
'''
def create_configuration(name=None):
    if not name:
        return False

    conf_path = os.path.join(settings.ODOO_ROOT_PATH, name, 'config')

    if not os.path.exists(conf_path):
        return False

    env = Environment(
        loader=PackageLoader('api', 'templates'),
        autoescape=select_autoescape(['j2'])
    )

    template = env.get_template(settings.ODOO_CONF_FILENAME + '.j2')

    template_rendered = template.stream({
        'admin_password': settings.ODOO_ADMIN_PASSWORD, 
        'db_host': settings.ODOO_DB_HOST,
        'db_port': settings.ODOO_DB_PORT,
        'db_name': name, 
        'db_user': settings.ODOO_DB_USER, 
        'db_password': settings.ODOO_DB_PASSWORD
    })

    template_rendered.dump(os.path.join(conf_path, settings.ODOO_CONF_FILENAME + '.conf'))

    return True

'''
'''
def create_database(name=None):
    if not name:
        return False

    cmd = 'createdb -U %s %s' % (settings.ODOO_DB_USER, name)
    return execute_command(settings.ODOO_DB_CONTAINER, cmd)

'''
'''
def copy_database_seed():
    backup_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'files', 'odoo.tar')
    return copy_in(settings.ODOO_DB_CONTAINER, '/tmp', backup_path)

'''
'''
def restore_database(name=None):
    if not name:
        return False

    cmd = 'psql -U %s -d %s -f %s' % (settings.ODOO_DB_USER, name, '/tmp/odoo.sql')
    return execute_command(settings.ODOO_DB_CONTAINER, cmd)

'''
'''
def remove_database_seed():
    cmd = 'rm -f %s' % ('/tmp/odoo.sql')
    return execute_command(settings.ODOO_DB_CONTAINER, cmd)

'''
'''
def create_odoo_container(name=None, ports=[]):
    if not name:
        return False

    ports = dict(map(lambda p: ('%d/tcp' % 8069, p), ports))
    volumes = dict(map(lambda f: (os.path.join(settings.ODOO_ROOT_PATH, name, f.strip()), {
        'bind': settings.ODOO_DEFAULT_FOLDERS[f].strip(),
        'mode': 'rw'
    })  , settings.ODOO_DEFAULT_FOLDERS))

    run_container(settings.ODOO_IMAGE, name, ports, volumes, settings.DOCKER_NETWORK_NAME)
    
    time.sleep(5)

    return True
