from draughtcraft.lib.units import InvalidUnitException
import math


class Calculations(object):

    def __init__(self, recipe):
        self.recipe = recipe

    #
    # Gravity and alcohol content calculations
    #
    @property
    def og(self):
        """
        Original gravity of the recipe.
        """

        points = 0
        volume = float(self.recipe.gallons)

        for a in self.recipe.additions:
            if a.fermentable:

                #
                # Default to the mash efficiency specified by the
                # recipe.
                efficiency = self.recipe.efficiency

                #
                # If the fermentable is extract, we don't take mash
                # efficiency into account - instead, we just use the
                # potential on record for the ingredient.
                #
                if a.fermentable.type == 'EXTRACT':
                    efficiency = 1

                try:
                    pounds = a.pounds
                    points += (
                        pounds * a.fermentable.ppg * efficiency) / volume
                except InvalidUnitException:
                    #
                    # If we can't convert the addition to pounds,
                    # don't include it in the gravity calculations.
                    #
                    pass

        return round(points / 1000 + 1, 3)

    @property
    def fg(self):
        """
        (Estimated) final gravity of the recipe based on yeast attenuation.
        """

        # Default the attenuation to 75%
        attenuation = .75

        #
        # If one or more yeast addition is specified,
        # use the highest attenuation available.
        #
        yeast = [a.yeast.attenuation
                 for a in self.recipe.additions
                 if a.yeast]
        if yeast:
            attenuation = max(yeast) or attenuation

        points = (self.og - 1) * 1000
        final = points - (points * attenuation)

        return round(final / 1000 + 1, 3)

    @property
    def abv(self):
        abv = (self.og - self.fg) * 131
        return round(abv, 1) / 100

    #
    # Color Calculations
    #
    @property
    def srm(self):
        total = 0
        fermentables = [a for a in self.recipe.additions if a.fermentable]
        gallons = float(self.recipe.gallons)
        for f in fermentables: