#
# Copyright 2019-Present Sonatype Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

"""pip.py gets installed pip dependencies"""
# pylint: disable=protected-access
import logging
import ast
import pkg_resources

from ..types.coordinates import Coordinates

class Pip():
  """pip.py gets installed pip dependencies"""
  def __init__(self, targets=None, requirements_file_path=None):
    self._log = logging.getLogger('jake')
    self._format = "pypi"
    self._working_set = pkg_resources.working_set
    self.requirements_file_path = requirements_file_path
    if targets:
      self._working_set = pkg_resources.WorkingSet(ast.literal_eval(targets))
    self._coords = self.generate_dependencies()

  def generate_dependencies(self, coords=Coordinates()) -> (Coordinates):
    """converts list of pkg_resource.working_set into purl coordinates"""

    if self.requirements_file_path:
      with open(self.requirements_file_path, 'r') as requirements_file:
        for line in requirements_file.readlines():
          name, version = line.strip().split('==')
          coords.add_coordinate(name, version, self._format)
    else:
      for i in iter(self._working_set):
        coords.add_coordinate(i.project_name, i._version, self._format)

    if len(coords.get_coordinates()) == 0:
      return None

    self._coords = coords
    return coords

  def get_dependencies(self) -> (Coordinates):
    """ gets the list of dependencies generatated on init
    Returns:
        Coordinates object -- list of coordinates generated by pkg_resources
    """
    return self._coords
