# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2016 Continuum Analytics, Inc.
#
# May be copied and distributed freely only as part of an Anaconda or
# Miniconda installation.
# -----------------------------------------------------------------------------
"""Project API."""

# Standard library imports
import os
import sys
import yaml


# Local imports
from anaconda_navigator.config import PROJECT_ENVS_FOLDER, PROJECT_YAML_FILE
from anaconda_navigator.utils.logs import logger


class Project(object):
    """
    An Anaconda project.

    Developed as part of Anaconda Navigator, details will initially only
    include information necessary for UI functions.
    """

    keys = ('name', 'default_environment', 'environments', 'commands', 'icon',
            'default_channels', 'is_app', 'dev_tool', 'version',
            'description', 'is_default', 'is_conda_app')
    root = sys.exec_prefix   # If someone runs from within an environment?

    def __init__(self, **kwargs):
        """
        An Anaconda project.

        Parameters
        ----------

        name : str
            Project name.
        description : str
            Project description.
        default_environment : str
            Currently selected env name.
        environments : dict
            {envname: specfile} set of env specs.
        commands : list of str
            [strings] executables.
        default_channels : list of str
            [strings] default channels for conda packages.
        is_app :bool
            regard as app?
        dev_tool : bool
            Whether can run other environments.
        icon : str
            Path to icon PNG file.
        is_default : bool
            Defines if the project is the default project.
        """
        self.name = 'default'
        self.description = ""
        self.default_channels = []
        self.version = "0.0.1"
        self.default_environment = 'default'
        self.environments = {'default': 'env.yaml'}
        self.commands = []

        self.icon = None

        # Ui client specifc
        self.is_default = False
        self.is_conda_app = False
        self.dev_tool = None
        # Is this redundant? having an endpoint should imply this?
        self.is_app = False

        for key, val in kwargs.items():
            setattr(self, key, val)

    def __getitem__(self, item, default=None):
        """Return dictionary value by attribute call."""
        return getattr(self, item, default)

    get = __getitem__

    def __repr__(self):
        """USed dictionary repr to represent project oobject."""
        return str(self.to_dict())

    def to_dict(self):
        """Dictionary representation of this project."""
        return {key: getattr(self, key) for key in self.keys}

    def save(self, path):
        """Write project details to file."""
        logger.debug(path)
        if not os.path.isdir(path):
            os.makedirs(path)

        data = yaml.safe_dump(self.to_dict(), default_flow_style=False)

        file_path = os.sep.join([path, PROJECT_YAML_FILE])

        with open(file_path, 'w') as f:
            f.write(data)

    def env_prefix(self, path):
        """If this project is at path, what's the current env prefix?."""
        if self.is_default:
            return self.root  # FIXME: Is this guaranteed to be the right one?

        return os.sep.join([path, PROJECT_ENVS_FOLDER,
                            self.default_environment])
