import tempfile
import yaml

from oslo_log import log

from kolla_kubernetes.commands.base_command import KollaKubernetesBaseCommand
from kolla_kubernetes.pathfinder import PathFinder
from kolla_kubernetes.service_resources import KollaKubernetesResources
from kolla_kubernetes.service_resources import Service
from kolla_kubernetes.utils import ExecUtils
from kolla_kubernetes.utils import FileUtils
from kolla_kubernetes.utils import JinjaUtils
from kolla_kubernetes.utils import YamlUtils

LOG = log.getLogger(__name__)
KKR = KollaKubernetesResources.Get()


class ResourceBase(KollaKubernetesBaseCommand):
    """Create, delete, or query status for kolla-kubernetes resources"""
    def get_parser(self, prog_name, skip_action=False):
        parser = super(ResourceBase, self).get_parser(prog_name)
        if not skip_action:
            parser.add_argument("action",
                                metavar="<action>",
                                help=("One of [%s]" %
                                      ("|".join(Service.VALID_ACTIONS))))
        parser.add_argument("resource_type",
                            metavar="<resource-type>",
                            help=("One of [%s]" %
                                  ("|".join(Service.VALID_RESOURCE_TYPES))))
if not os.path.exists(password_file):
    print ("You need to generate password file before using this script")
    exit(3)

with open(password_file, 'r') as stream:
    try:
        passwords = yaml.safe_load(stream)
    except yaml.YAMLError as exc:
        print(exc)
for element in passwords:
    if isinstance(passwords[element], basestring):
        service_name = element.replace('_', '-')
        password_value = passwords[element]
        nsname = 'kolla_kubernetes_namespace'
        nsname = KollaKubernetesResources.GetJinjaDict()[nsname]
        if command == "create":
            command_line = 'kubectl create secret generic {} {}{} {}{}'.format(
                           service_name,
                           " --from-literal=password="******"--namespace=",
                           nsname)
        else:
            command_line = "kubectl delete secret {} --namespace={}".format(
                           service_name, nsname)
        try:
            res = subprocess.check_output(
                command_line, shell=True,
                executable='/bin/bash')
            res = res.strip()  # strip whitespace