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

from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
                        unicode_literals, with_statement)

import hashlib

from pants.backend.codegen.targets.java_thrift_library import JavaThriftLibrary
from pants.base.fingerprint_strategy import FingerprintStrategy


class JavaThriftLibraryFingerprintStrategy(FingerprintStrategy):
  """Scrooge cares about a thrift target's `language` and `rpc_style` in addition to its payload.

  As such this strategy ensures new code is generated by scrooge whenever `language` or `rpc_style`
  changes.
  """

  def __init__(self, thrift_defaults):
    self._thrift_defaults = thrift_defaults

  def compute_fingerprint(self, target):
    fp = target.payload.fingerprint()
    if not isinstance(target, JavaThriftLibrary):
      return fp

    hasher = hashlib.sha1()
    hasher.update(fp)
    hasher.update(self._thrift_defaults.language(target))
    hasher.update(self._thrift_defaults.rpc_style(target))
    return hasher.hexdigest()

  def __hash__(self):
    return hash((type(self), self._thrift_defaults))

  def __eq__(self, other):
    return type(self) == type(other) and self._thrift_defaults == other._thrift_defaults
