# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from django.conf import settings
from tastypie.resources import Resource
from tastypie.utils import trailing_slash
from core.models.request import Request
from api.utils.odoo_api import (
    normalize_name,
    check_name,
    randomize_port,
    create_folders,
    create_configuration,
    create_database,
    copy_database_seed,
    restore_database,
    remove_database_seed,
    create_odoo_container,
    apply_permissions
)
from api.utils.jwt_token import get_user
from api.utils.jwt_authentication import JWTAuthentication
from simplejson import JSONDecodeError
import simplejson as json

class OdooResource(Resource):
    class Meta:
        authentication = JWTAuthentication()

    '''
    '''
    def prepend_urls(self):
        return [
            url(r'^(?P<resource_name>%s)/create%s$' % (self._meta.resource_name, trailing_slash), self.wrap_view('odoo_create'), name='api_odoo_create'),
        ]
    
    '''
    '''
    def odoo_create(self, request, **kwargs):
        self.method_check(request, allowed='post')
        self.is_authenticated(request)

        authorization_header = request.META.get(settings.JWT_ACCEPT_HEADER)
        prefix_length = len(settings.JWT_PREFIX_HEADER)
        user = get_user(authorization_header[prefix_length + 1:])

        name = None
        try:
            data = json.loads(request.body)
            name = data['name']
        except JSONDecodeError:
            name = None
        except KeyError:
            name = None

        r = Request.objects.create(name='Crear contenedor Odoo')
        r.user = user

        if not name:
            r.issue = 'name is required'
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': 'name is required'
            })

        # 1. Check and get name
        name = normalize_name(name)
        name_exists = check_name(name)

        if name_exists:
            r.issue = '%s: name is already exists' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: name is already exists' % name
            })
        
        # 2. Get port
        port = randomize_port()

        # 3. Folder structure create
        folders_created = create_folders(name)

        if not folders_created:
            r.issue = '%s: folders structure cannot be created' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: folders structure cannot be created' % name
            })

        # 4. Configuration create
        conf_created = create_configuration(name)

        if not conf_created:
            r.issue = '%s: configuration cannot be created' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: configuration cannot be created' % name
            })

        # 5. Database create
        db_created = create_database(name)

        if not db_created:
            r.issue = '%s: database cannot be created' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: database cannot be created' % name
            })

        # 6. Copy a database backup
        seed_copied = copy_database_seed()

        if not seed_copied:
            r.issue = '%s: database seed cannot be copied' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: database seed cannot be copied' % name
            })
        
        # 7. Restore database schema 
        db_restored = restore_database(name)
        
        if not db_restored:
            r.issue = '%s: database cannot be restored' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: database cannot be restored' % name
            })

        # 8. Remove unused bakup file
        seed_removed = remove_database_seed()

        if not seed_removed:
            r.issue = '%s: seed cannot be removed' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: seed cannot be removed' % name
            })


        # 9. Odoo create
        odoo_created = create_odoo_container(name, [port])

        if not odoo_created:
            r.issue = '%s: odoo container cannot be created' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: odoo container cannot be created' % name
            })

        # 10. Apply permissions 
        permissions_applied = apply_permissions(name)

        if not permissions_applied:
            r.issue = '%s: odoo container cannot be started' % name
            r.status = 5
            r.save()

            return self.create_response(request, {
                'error_message': '%s: odoo container cannot be started' % name
            })

        r.issue = '%s: odoo container created successfully' % name
        r.status = 4
        r.save()
        
        return self.create_response(request, {
            'action': {
                'type': 'redirect',
                'ip': settings.SERVER_IP,
                'port': port
            }
        })