"""
ProjectFile
"""
import yaml
import datetime
import os
from mlops.utils.logger import logger


class ProjectFile:

    def __init__(self, config, path='.', projectfile_name='MLproject', use_localhost=False, clean_projectfile=True):
        self.config = config
        self.projectfile_name = projectfile_name
        self.project_path = os.path.join(path, projectfile_name)

        # Clean projectfile if it exists
        if clean_projectfile and os.path.exists(self.project_path):
            logger.debug('Removing existing project file: {0}'.format(self.project_path))
            os.remove(os.path.join(path, self.projectfile_name))

        if use_localhost:
            volume_path = config['project']['LOCAL_VOLUME_MOUNT']
        else:
            volume_path = config['project']['VOLUME_MOUNT']

        self.project_dict = {'name': config['project']['NAME'].lower(),
                             'docker_env': {'volumes': [volume_path],
                                            'image': config['project']['NAME'].lower()}}

        self._parse_entry_points()

    def _parse_entry_points(self):
        entry_points_dict = {}
        for key in self.config['entry_points']:
            entry_points_dict[key] = {'command': self.config['entry_points'][key]}
        self.project_dict['entry_points'] = entry_points_dict

    def generate_yaml(self):
        logger.info('Writing project file: {0}'.format(self.project_path))
        with open(self.project_path, 'w+') as f:
            f.write('# {0}: This ProjectFile was automatically generated by MLOps\n\n'.format(datetime.datetime.now()))
            yaml.dump(self.project_dict, f, default_flow_style=False, sort_keys=False)
