#!/usr/bin/python
#
# Copyright (c) 2016 Akanda, Inc. All Rights Reserved.
#
# 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 pprint
import argparse
import os
import sys

from prettytable import PrettyTable

from keystoneclient.auth.identity import v3 as ksv3
from keystoneclient import session as kssession
from neutronclient.v2_0 import client
from neutronclient.common import exceptions as neutron_exc

class ByoExtClientWrapper(client.Client):
    byonf_path = '/byonf'
    byonfs_path = '/byonfs'


    @client.APIParamsCall
    def create_byonf(self, byonf):
        return self.post(
            self.byonf_path,
            body={'byonf': byonf}
        )

    def update_byonf(self, byonf):
        if not byonf.get('id'):
            print 'ERROR: must specify id of byonf assocation to update'
            sys.exit(1)

        path = self.byonf_path + '/' + byonf.pop('id')
        return self.put(
            path,
            body={'byonf': byonf}
        )

    @client.APIParamsCall
    def list_byonfs(self, retrieve_all=True, **_params):
        return self.list('byonfs', self.byonf_path, retrieve_all, **_params)

    @client.APIParamsCall
    def delete_byonf(self, byonf_id):
        return self.delete('%s/%s' % (self.byonf_path, byonf_id))

ks_args = {
    'auth_url': os.getenv('OS_AUTH_URL', 'http://127.0.0.1:5000/v3'),
    'username': os.getenv('OS_USERNAME', 'demo'),
    'password': os.getenv('OS_PASSWORD', 'secrete'),
    'project_name': os.getenv('OS_PROJECT_NAME', 'demo'),
    'user_domain_id': 'default',
    'project_domain_id': 'default',
}

auth = ksv3.Password(**ks_args)
ks_session = kssession.Session(auth=auth)
api_client = ByoExtClientWrapper(
    session=ks_session,
)


parser = argparse.ArgumentParser(description="Script to manage user network functions")
parser.add_argument('action', default='list')
parser.add_argument('--function', default='')
parser.add_argument('--image_id')
parser.add_argument('--driver')
parser.add_argument('--id')
parser.add_argument('--tenant_id')


args = parser.parse_args()

def print_table(byonfs):
    if not isinstance(byonfs, list):
        byonfs = [byonfs]

    columns = ['id', 'tenant_id', 'function_type', 'driver', 'image_id']
    table = PrettyTable(columns)
    for byonf in byonfs:
        table.add_row([byonf.get(k) for k in columns])
    print table

if args.action in ['create', 'update']:
    req_args = {
        'image_id': args.image_id,
        'function_type': args.function,
        'driver': args.driver,
    }
    if args.tenant_id:
        req_args['tenant_id'] = args.tenant_id
    if args.id:
        req_args['id'] = args.id

    f = getattr(api_client, '%s_byonf' % args.action)
    result = f(req_args)
    print_table(result['byonf'])

elif args.action == 'delete':
    api_client.delete_byonf(args.id)
    print 'deleted byonf assocation with id %s' % args.id
else:
    arg2 = {}
    if args.function:
        arg2['function_type'] = args.function
    print_table(api_client.list_byonfs(**arg2)['byonfs'])
