# -*- coding: utf-8 -*-

"""
Copyright (C) 2013 Dariusz Suchojad <dsuch at zato.io>

Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""

from __future__ import absolute_import, division, print_function, unicode_literals

# stdlib
import logging

# Zato
from zato.admin.web.forms import ChangePasswordForm
from zato.admin.web.forms.definition.cassandra import CreateForm, EditForm
from zato.admin.web.views import change_password as _change_password, CreateEdit, Delete as _Delete, Index as _Index, method_allowed
from zato.common import CASSANDRA
from zato.common.odb.model import CassandraConn

logger = logging.getLogger(__name__)

class Index(_Index):
    method_allowed = 'GET'
    url_name = 'def-cassandra'
    template = 'zato/definition/cassandra.html'
    service_name = 'zato.definition.cassandra.get-list'
    output_class = CassandraConn
    paginate = True

    class SimpleIO(_Index.SimpleIO):
        input_required = ('cluster_id',)
        output_required = ('id', 'name', 'is_active', 'contact_points', 'port', 'exec_size',
            'proto_version', 'default_keyspace')
        output_optional = ('username', 'cql_version')
        output_repeated = True

    def handle(self):
        return {
            'default_port': CASSANDRA.DEFAULT.PORT.value,
            'default_exec_size': CASSANDRA.DEFAULT.EXEC_SIZE.value,
            'default_proto_version': CASSANDRA.DEFAULT.PROTOCOL_VERSION.value,
            'create_form': CreateForm(),
            'edit_form': EditForm(prefix='edit'),
            'change_password_form': ChangePasswordForm()
        }

class _CreateEdit(CreateEdit):
    method_allowed = 'POST'

    class SimpleIO(CreateEdit.SimpleIO):
        input_required = ('cluster_id', 'name', 'is_active', 'contact_points', 'port', 'exec_size',
            'proto_version', 'default_keyspace')
        input_optional = ('username', 'cql_version', 'tls_ca_certs', 'tls_client_cert', 'tls_client_priv_key')
        output_required = ('id', 'name')

    def success_message(self, item):
        return 'Successfully {0} the connection [{1}]'.format(self.verb, item.name)

class Create(_CreateEdit):
    url_name = 'definition-cassandra-create'
    service_name = 'zato.definition.cassandra.create'

class Edit(_CreateEdit):
    url_name = 'definition-cassandra-edit'
    form_prefix = 'edit-'
    service_name = 'zato.definition.cassandra.edit'

class Delete(_Delete):
    url_name = 'definition-cassandra-delete'
    error_message = 'Could not delete the connection'
    service_name = 'zato.definition.cassandra.delete'

@method_allowed('POST')
def change_password(req):
    return _change_password(req, 'zato.definition.cassandra.change-password')
