#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import logging
import os
import re
import string
import subprocess
import sys

import six


# Initialize logging
logging.basicConfig(
    format='%(asctime)s [%(levelname)s] %(name)s - %(message)s',
    level=logging.WARNING)
_log = logging.getLogger()
_log.setLevel(logging.INFO)


class Gbp_Config(object):

    def __init__(self):
        self.err_strings = ['Unable', 'Conflict', 'Bad Request',
                            'Error', 'Unknown', 'Exception', 'Invalid',
                            'read-only', 'not supported',
                            'prefix greater than subnet mask',
                            'reference the non shared resource',
                            'cannot be shared by driver']

    def keystone_creds(self):
        creds = {}
        creds['username'] = os.environ['OS_USERNAME']
        creds['password'] = os.environ['OS_PASSWORD']
        creds['auth_url'] = os.environ['OS_AUTH_URL']
        creds['tenant_name'] = os.environ['OS_TENANT_NAME']
        return creds

    def get_uuid(self, cmd_out):
        match = re.search("\\bid\\b\s+\| (.*) \|", cmd_out, re.I)
        if match is not None:
            obj_uuid = match.group(1)
            return obj_uuid.rstrip()
        else:
            return 0

    def gbp_action_config(self, cmd_val, name_uuid, **kwargs):
        """
        -- cmd_val== 0:delete; 1:create; 2:update
        -- name_uuid == UUID or name_string
        Create/Update/Delete Policy Action
        Returns assigned UUID on Create
        kwargs addresses the need for passing required/optional params
        """
        if cmd_val == '' or name_uuid == '':
            _log.info('''Function Usage: gbp_action_config 0 "abc"\n
                       --cmd_val == 0:delete; 1:create; 2:update\n
                       -- name_uuid == UUID or name_string\n''')
            return 0
        # Build the command with mandatory param 'name_uuid'
        if cmd_val == 0:
            cmd = 'gbp policy-action-delete ' + str(name_uuid)
        if cmd_val == 1:
            cmd = 'gbp policy-action-create ' + str(name_uuid)
        if cmd_val == 2:
            cmd = 'gbp policy-action-update ' + str(name_uuid)
        # Build the cmd string for optional/non-default args/values
        for arg, value in list(kwargs.items()):
            cmd = cmd + " --" + ("%s %s" % (arg, value))
        _log.info(cmd)
        # Execute the policy-action-config-cmd
        cmd_out = subprocess.getoutput(cmd)
        _log.info(cmd_out)
        # Catch for non-exception error strings, even though try clause
        # succeeded
        if self.cmd_error_check(cmd_out) == 0:
            return 0
        # If "create" cmd succeeded then parse the cmd_out to extract the UUID
        if cmd_val == 1:
            action_uuid = self.get_uuid(cmd_out)
            return action_uuid

    def gbp_classif_config(self, cmd_val, classifier_name, **kwargs):
        """