#!/usr/bin/env python
# -*- coding: utf-8 -*-
import carbonlifecycle

EPSILON = 0.001

def setup_module():
    global lc
    stock = {'Volume': {(1., 1.): 100., (1., 2.): 100.,
                        (8., 1.): 100., (8., 2.): 100.,
                        (3., 1.): 100.}
            }
    lc = carbonlifecycle.ProductLifeCycle(1., stock, 117.952347)

def test_constants():
    for sp, prod in carbonlifecycle.LOG2PROD.iteritems():
        assert sum(prod.values()) == 1.0
    for sp, prod in carbonlifecycle.PULP2PROD.iteritems():
        assert sum(prod.values()) == 1.0
    for sp, prod in carbonlifecycle.PROD_CONVERSION.iteritems():
        for p, conv in prod.iteritems():
            assert sum(conv.values()) == 1.0

def test_init():
    assert lc._stock[('pine', 'log')] == 200.
    assert lc._stock[('pine', 'pulp')] == 200.
    assert lc._stock[('birch', 'log')] == 100.

def test_cutting():
    lc._cutting()
    assert lc.c_flow[0] == [10.]

def test_manufacturing():
    lc._manufacturing()
    print lc._sawn_timber
    assert abs(lc._sawn_timber - 47938.) < EPSILON
    print lc._plywood
    assert abs(lc._plywood - 20748.) < EPSILON
    print lc._mechanical_pulp
    assert abs(lc._mechanical_pulp - 1724.22) < EPSILON
    print lc._chemical_pulp
    assert abs(lc._chemical_pulp - 69505.08) < EPSILON
    # self._mwh2c_ref adjusted so that energy production is c neutral
    print lc.c_flow
    assert abs(lc.c_flow[0][-2]) < EPSILON
    assert abs(lc.c_flow[0][-1] -  6414.457) < EPSILON
    print lc._product
    tot_mass = 0.
    for pr, cats in lc._product.iteritems():
        for cat, mass in cats.iteritems():
            tot_mass += mass
    assert tot_mass == lc._sawn_timber + lc._plywood + lc._mechanical_pulp +\
                       lc._chemical_pulp

def test_yr_release():
    lc._yr_release(1)
    t_long =  lc._product['sawn timber']['long'] - lc._hl['sawn timber']['long']
    print t_long
    assert abs(t_long - 442.184330038) < EPSILON
    print abs(lc.c_flow[1][-1] - 0.) < EPSILON
    f_m_st =  lc._product['fiber']['medium-short'] -\
              lc._hl['fiber']['medium-short']
    f_s =  lc._product['fiber']['short'] - lc._hl['fiber']['short']
    f_prod = .5 * .48 * (f_m_st + f_s)
    print lc._product
    print abs(lc.c_flow[1][0] - f_prod) < EPSILON
