import os
import petl
from dotenv import load_dotenv
load_dotenv()


class CLIRunner:
    def __init__(self,
                 # service_name=None,
                 source=None,
                 connection=None,
                 **kwargs):

        self.source = source
        self.connection = connection

    def conf(self, var_name, default=None):
        return self.connection.params.get(var_name,
                                          self.source.params.get(var_name,
                                                                 os.getenv(var_name, default))) # noqa E501

    def run_cmd(self, cmd, headers=[], **kwargs):
        '''Run cmd return stream of data.'''

        # run sqlplus with credentials, pointing at .sql file
        source = petl.PopenSource(cmd)
        # read data
        # delimiter = self.source.params.get('delimiter', ',')

        # table = petl.fromcsv(source, delimiter=delimiter)
        table = petl.fromcsv(source)

        if headers:
            table = table.pushheader(headers)

        for header in headers:
            table = table.convert(header, lambda v: v.strip())

        return table
