# coding=utf-8
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).

from __future__ import absolute_import, division, print_function, unicode_literals

import os
import unittest
from builtins import object, str

from mock import Mock

from pants.backend.jvm.artifact import Artifact
from pants.backend.jvm.repository import Repository
from pants.backend.jvm.scala_artifact import ScalaArtifact
from pants.backend.jvm.targets.jar_library import JarLibrary
from pants.backend.jvm.targets.java_library import JavaLibrary
from pants.backend.jvm.tasks.jar_publish import JarPublish
from pants.base.exceptions import TaskError
from pants.build_graph.build_file_aliases import BuildFileAliases
from pants.build_graph.target import Target
from pants.scm.scm import Scm
from pants.util.contextutil import temporary_dir
from pants.util.dirutil import safe_mkdir, safe_walk
from pants_test.task_test_base import TaskTestBase


class JarPublishTest(TaskTestBase):

  @classmethod
  def task_type(cls):
    return JarPublish

  def test_smoke_publish(self):
    with temporary_dir() as publish_dir:
      self.set_options(local=publish_dir)
      task = self.create_task(self.context())
      task.execute()

  @classmethod
  def alias_groups(cls):
    cls.push_db_basedir = os.path.join(cls._build_root(), "pushdb")
    safe_mkdir(cls.push_db_basedir)

    return BuildFileAliases(
      targets={
        'jar_library': JarLibrary,
        'java_library': JavaLibrary,
        'target': Target,
      },
      objects={
        'artifact': Artifact,
        'scala_artifact': ScalaArtifact,
        'internal': Repository(name='internal', url='http://example.com',
                               push_db_basedir=cls.push_db_basedir),
      },
    )

  def _prepare_for_publishing(self, with_alias=False):
    targets = []
    nail_target = self._create_nail_target()
    targets.append(nail_target)

    shoe_target = self.create_library('b', 'java_library', 'b', ['B.java'],
      provides="artifact(org='com.example', name='shoe', repo=internal)",
      dependencies=[nail_target.address.reference()])
    targets.append(shoe_target)

    shoe_address = shoe_target.address.reference()
    if with_alias:
      # add an alias target between c and b
      alias_target = self.create_library('z', 'target', 'z', dependencies=[shoe_address])
      targets.append(alias_target)
      horse_deps = [alias_target.address.reference()]
    else:
      horse_deps = [shoe_address]

    horse_target = self.create_library('c', 'java_library', 'c', ['C.java'],
      provides="artifact(org='com.example', name='horse', repo=internal)",
      dependencies=horse_deps)
    targets.append(horse_target)
    return targets

  def _create_nail_target(self):