<?php

namespace Gaia\Stockpile;

use Gaia\DB\Transaction;
use Gaia\Test\Tap;
$user_id = uniqueUserID();
$item_id = uniqueNumber(1, 1000000);
// test transaction support.
Transaction::claimStart();
$total = stockpile($app, $user_id)->add($item_id);
Tap::is(quantify($total), 4, 'add inside a transaction');
// revert the transaction
Transaction::rollback();
$total = stockpile($app, $user_id)->get($item_id);
Tap::is(quantify($total), 3, 'after txn rollback, the value we added isnt there');
// add inside a transaction and commit it.
Transaction::claimStart();
$total = stockpile($app, $user_id)->add($item_id);
Tranaction::commit();
$total = stockpile($app, $user_id)->get($item_id);
Tap::is(quantify($total), 4, 'add inside of a transaction and commit it. now we can see it!');
$q = $stockpile->get($item_id);
Tap::is(lastElement($q->all()), array(), 'empty properties before callback validator is attached');
$stockpile = new QuantityInspector($stockpile, 'Gaia\\Stockpile\\sanitizeQuantity');
$q = $stockpile->get($item_id);
Tap::is(lastElement($q->all()), array('xp' => 1), 'callback function populated xp into read quantity object');
$stockpile = new QuantityInspector(stockpile($app, $user_id), 'Gaia\\Stockpile\\sanitizeQuantity');
$item_id = uniqueNumber(1, 10000000);
$res = $stockpile->add($item_id, 1);
Tap::is(lastElement($res->all()), array('xp' => 1), 'callback function populated xp into the quantity on add');
$user_id = uniqueUserID();
$item_id = uniqueNumber(1, 10000000);
$stockpile = stockpile($app, $user_id);
$total = $stockpile->add($item_id, 3);
Tap::is($stockpile->set($item_id, $total), $total, 'When calling set with the same set of serials, no items created or subtracted');
$new = $total->grab(array(lastElement($total->serials())));
Tap::is($stockpile->set($item_id, $new), $new, 'When removing  a serial, everything matches up');
Tap::is($stockpile->set($item_id, $total), $total, 'When adding back a serial, everything matches up');
$user_id1 = uniqueUserID();
$user_id2 = uniqueUserID();
$item_id = uniqueNumber(1, 10000000);
Transaction::reset();
Transaction::claimStart();
$stockpile1 = stockpile($app, $user_id1);
$stockpile2 = stockpile($app, $user_id2);
$start = microtime(TRUE);
$total1 = $stockpile1->add($item_id);
$total2 = $stockpile2->add($item_id);
Transaction::commit();
$elapsed = microtime(TRUE) - $start;
Tap::cmp_ok($elapsed, '<', 1, 'two users adding the same item doesnt create deadlock. took ' . number_format($elapsed, 2) . ' seconds');
Tap::isnt($total1, $total2, 'the items created for these two users are different');