from tlpytools.log import logger
from tlpytools.data import data_tables
import yaml


class run_yaml():
    """usage: run in order
    - load_yaml
    - load_yaml_data
    - run_steps
    """
    def load_yaml(self, filename=None):
        """
        returns yaml file as object
        """
        if filename == None:
            filename = "{}.yaml".format(type(self).__name__)
        with open(filename) as f:
            s = yaml.load(f, Loader=yaml.SafeLoader)
            return s

    def load_yaml_data(self, s):
        """load yaml global variables and dataframe, and return them.

        Args:
            s (setting from load_yaml): setting from load_yaml

        Returns:
            s, dfd: setting and dataframe dictionary
        """

        # read variables all as globals
        if 'VARS' in s:
            for var in s['VARS'].keys():
                setattr(self, var, s['VARS'][var])
            # remove VARS from spec dictionary
            del s['VARS']

        # read table data
        dfd = data_tables.read_tbl_data(s)

        return s, dfd

    def run_steps(self, s, log=None):
        """run steps specified in setting s

        Args:
            s (dict): specification from yaml
            log (object): logger object
        """
        # handle no logger
        if log == None:
            log = logger()
            log.init_logger()

        # perform steps
        for step in s["STEPS"]:
            log.info("===={}====".format(step))
            if step not in s:
                s[step] = None
            eval("self.{}".format(step))(spec=s[step], files=s["FILES"])

    def export_data_csv(self, spec, files):
        """wrapper function for exporting file outputs as csv;
        self.dfd must contain DataFrame tables for export.

        Args:
            spec (dict): large specification containing the imputation settings, see yaml file under 'impute_hh_income'
            files (dict):  a list of input and output file names
        """
        data_tables.export_csv(dict_df=self.dfd, ofiles=files['OUTPUTS'])

    def export_data_files(self, spec, files):
        """wrapper function for exporting file outputs as csv;
        self.dfd must contain DataFrame tables for export.

        Args:
            spec (dict): large specification containing the imputation settings, see yaml file under 'impute_hh_income'
            files (dict):  a list of input and output file names
        """
        data_tables.export_data(dict_df=self.dfd, ofiles=files['OUTPUTS'])

    @staticmethod
    def get_sample_spec():
        """returns a sample data specificationf or config
        """
        example_spec = {
            '__COMMENT__': 'THIS IS AN AUTOGENERATED YAML FILE example.',
            'FILES': {
                'INPUTS': {
                    'tbl1': "td_2017.tbl1.crypt",
                    'tbl2': "td_2017.tbl2.sqlsvr",
                    'tbl3': "data_files/tbl3.csv",
                },
                'INPUT_COLUMNS': {
                    'tbl_blended_skim': ['col1', 'col2', 'col3']
                },
                'OUTPUTS': {
                    'tblOut1': "tblOut1.csv",
                }
            },
            'VARS': {
                'colTAZ': 'TAZ',
                'colSubSeed': 'SubSeedGeo',
                'colSeed': 'SeedGeo',
                'tblCTName': 'tblCTMV',
                'tblGeoName': 'tblGeo',
                'tblHHWgtName': 'tblHHWeights',
                'geoStructure': 'A1_9_44',
                'clearMem': True
            },
            'STEPS': ['example_step1'],
            'example_step1': {
                'test': 'test_val'
            }
        }

        return example_spec
