#!/usr/bin/env python

import argparse
import pyeapi

def get_results(command):
    return command[0]['result']

'''This evaluates True if the value exists and false if it does not exist'''
def check_vlan(connection, vlan_id):
    vlan_id = str(vlan_id)
    command = 'show vlan id {}'.format(vlan_id)
    try:
        connection = connection.enable(command)
        connection=get_results(connection)
        connection=connection['vlans'][vlan_id]
        if connection:
            return True
    except pyeapi.eapilib.CommandError:
        print "False"
        return False

def main():
    #parser - description when -help function used.
    parser = argparse.ArgumentParser(description="Used to add or remove a vlan, if vlan exists do nothing")
    #add_arguement - adding user defined variables, storing variables vlan_id, vlan_name, and False.
    parser.add_argument("vlan_id", help="VLAN number to create or remove", action="store", type=int)
    parser.add_argument("--name", help="Specify VLAN name", action="store", dest="vlan_name", type=str)
    parser.add_argument("--remove", help="Remove the given VLAN ID", action="store_true")
    cli_args = parser.parse_args()
    vlan_id = cli_args.vlan_id
    remove = cli_args.remove
    vlan_name = cli_args.vlan_name
    connection = pyeapi.connect_to("pynet-sw1")
    if vlan_id and vlan_name:
        if check_vlan(connection=connection, vlan_id=vlan_id) is False:
            '''Vlan is not present and but config parameters are present'''
            command_str1 = 'vlan {}'.format(vlan_id)
            cmd = [command_str1]
            command_str2 = 'name {}'.format(vlan_name)
            cmd.append(command_str2)
            connection.config(cmd)
            print "vlan {}, {} added".format(vlan_name,vlan_id)
        else:
            print "No change was made, {} present.".format(vlan_id)
    elif remove and vlan_id:
        if check_vlan(connection=connection, vlan_id=vlan_id) is True:
            '''The vlan is present and so is remove statement, remove the vlan'''
            command_str = 'no vlan {}'.format(vlan_id)
            connection.config([command_str])
            print "vlan {} remove".format(vlan_id)
        else:
            print "No change was made, {} not present".format(vlan_id)
    else:
        print "No change was made and I don't know why."


if __name__ == "__main__":
    main()
