<?php

use Gaia\Test\Tap;
use Gaia\Time;
use Gaia\DB;
if (!isset($seller_id)) {
    $seller_id = uniqueUserId();
}
if (!isset($buyer_id)) {
    $buyer_id = uniqueUserId();
}
if (!isset($item_id)) {
    $item_id = uniqueNumber(1, 100000);
}
$souk = souk($app, $seller_id);
$listing = $souk->auction(array('price' => 10, 'bid' => 0, 'item_id' => $item_id));
Tap::isa($listing, 'Gaia\\Souk\\Listing', 'create returns a souk listing object');
Tap::is($listing->price, 10, 'price returned is 10');
Tap::is($listing->step, 1, 'step is one if no step specified');
Tap::is($listing->bid, 0, 'opening bid is zero');
Tap::is($listing->seller, $seller_id, 'seller matches the user id we passed in');
Tap::is($listing->closed, 0, 'auction not closed yet');
Tap::is($listing->buyer, 0, 'no buyer yet');
Tap::is($listing->bidder, 0, 'no bidder either');
Tap::is($listing->touch, 0, 'auction hasnt been touched yet');
Tap::cmp_ok(abs($listing->created - Time::now()), '<', 2, 'created matches current time');
Tap::is($listing->expires - $listing->created, 86400 * 14, 'when no expires time set, defaults to 2 weeks');
Tap::is($listing, $souk->get($listing->id), 'get by id returns same item we got back from auction step');
Tap::is(array($listing->id => $listing), $souk->fetch(array($listing->id)), 'fetch by id returns same item we got back from auction step');
Time::offset(86400 * 15);
$listing = $souk->close($listing->id);
$res = array();
foreach (souk($app)->fetch(souk($app)->search(array('item_id' => $item_id, 'seller' => $seller_id, 'floor' => 4, 'ceiling' => 6))) as $id => $listing) {
    $res[$listing->price] = TRUE;
}
$res = array_keys($res);
sort($res);
Tap::is($res, array(4, 5, 6), 'setting floor and ceiling limits the result set to prices in the correct range');
$search = souk($app)->search(array('item_id' => $item_id, 'seller' => $seller_id, 'closed' => 0));
$id = array_shift($search);
souk($app)->close($id);
$ids = souk($app)->search(array('item_id' => $item_id, 'seller' => $seller_id, 'closed' => 0));
Tap::ok(!in_array($id, $ids, TRUE), 'after closing an item, it no longer appears in the list of unclosed items');
$res = souk($app)->fetch(souk($app)->search(array('item_id' => $item_id, 'seller' => $seller_id, 'closed' => 0, 'only' => 'bid')));
$bidonly = TRUE;
foreach ($res as $listing) {
    if (!$listing->step || $listing->price) {
        $bidonly = FALSE;
    }
}
Tap::ok($bidonly, 'searching with only=>bid param returns results that are all bid only items, no prices');
$res = souk($app)->fetch(souk($app)->search(array('item_id' => $item_id, 'seller' => $seller_id, 'closed' => 0, 'only' => 'buy')));
$buynow = TRUE;
foreach ($res as $listing) {
    if ($listing->step || !$listing->price) {
        $buynow = FALSE;
    }
}
Tap::ok($buynow, 'searching with only=>buy param returns results that are all buy now only items, no bids');
unset($seller_id);
unset($buyer_id);
unset($item_id);