# -*- coding: utf8 -*-
# Copyright (c) 2019 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
# sell copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.

from nr.databind.core import Field, Struct
from nr.interface import implements, override
from nr.stream import Stream
from shore.core.plugins import IPackagePlugin, IPublishTarget
from shore.model import Package
from typing import Iterable
import logging
import os
import subprocess
import sys

logger = logging.getLogger(__name__)


def _resolve_envvars(s):
  if s and s.startswith('$'):
    value = os.getenv(s[1:])
    if not value:
      raise RuntimeError('environment variable {} is not set.'.format(s))
    return value
  return s


@implements(IPublishTarget)
class TwinePublishTarget(Struct):
  name = Field(str)
  selectors = Field([str])
  repository = Field(str, default=None)
  repository_url = Field(str, default=None)
  test_repository = Field(str, default=None)
  test_repository_url = Field(str, default=None)
  sign = Field(bool, default=False)
  sign_with = Field(str, default=None)
  identity = Field(str, default=None)
  username = Field(str, default=None)
  password = Field(str, default=None)
  test_username = Field(str, default=None)
  test_password = Field(str, default=None)
  skip_existing = Field(bool, default=False)
  cert = Field(str, default=None)
  client_cert = Field(str, default=None)

  def get_name(self) -> str:
    return self.name

  def get_build_selectors(self) -> Iterable[str]:
    return self.selectors

  def publish(self, builds, test, build_directory, skip_existing):
    files = Stream.concat(x.get_build_artifacts() for x in builds)
    files = files.map(lambda x: os.path.join(build_directory, x)).collect()
    command = [sys.executable, '-m', 'twine', 'upload']

    repo = self.test_repository if test else self.repository
    repo_url = self.test_repository_url if test else self.repository_url
    username = self.test_username if test else self.username
    password = self.test_password if test else self.password

    username = _resolve_envvars(username)
    password = _resolve_envvars(password)

    if not repo and not repo_url:
      prefix = 'test_' if test else ''
      raise RuntimeError('missing {0}repository or {0}repository_url for PypiPublisher'.format(prefix))

    if repo:
      command += ('--repository', repo)
    if repo_url:
      command += ('--repository-url', repo_url)
    if self.sign:
      command.append('--sign')
    if self.sign_with:
      command += ('--sign-with', self.sign_with)
    if self.identity:
      command += ('--identity', self.identity)
    if username is not None:
      command += ('--username', username)
    if password is not None:
      command += ('--password', password)
    if self.skip_existing:
      command.append('--skip-existing')
    if self.cert:
      command += ('--cert', self.cert)
    if self.client_cert:
      command += ('--client-cert', self.client_cert)
    if skip_existing:
      command.append('--skip-existing')
    command += files
    command += ['--verbose']

    logger.debug('invoking twine: %s', command)
    subprocess.check_call(command)


@implements(IPackagePlugin)
class PypiPublisher:
  """ A publisher for builds generated by the "setuptools" plugin using the
  Twine command-line. """

  class Config(Struct):
    name = Field(str, default='pypi')
    consumes = Field([str], default=['setuptools'])
    repository = Field(str, default=None)
    repository_url = Field(str, default=None)
    username = Field(str, default=None)
    password = Field(str, default=None)
    test_repository = Field(str, default=None)
    test_repository_url = Field(str, default=None)
    test_username = Field(str, default=None)
    test_password = Field(str, default=None)

  @override
  @classmethod
  def get_default_config(cls):
    return cls.Config(repository='pypi', test_repository='testpypi')

  @override
  def get_package_publish_targets(self, package: Package) -> Iterable[IPublishTarget]:
    config = self.config
    yield TwinePublishTarget(
      config.name,
      config.consumes,
      config.repository,
      config.repository_url,
      config.test_repository,
      config.test_repository_url,
      username=config.username,
      password=config.password,
      test_username=config.test_username,
      test_password=config.test_password)
