<?php

/**
 * 同步游戏表
 * User: solu
 */
class Sync_Game extends Sync_Base {
    protected $dbKey = 'dw_baccarat';
    protected $frequency = 1;
    protected $index = 2;

    protected $dataField = ['game_state', 'update_time_int', 'create_block_num'];

    /**
     * 清除数据的时间间隔
     * @var int
     */
    protected $clearTtl = 600;
    protected $clearAction = 'cleargame';

    public function __construct() {
        parent::__construct('game', 'id', 'update_time_int');
    }

    protected function addNewRows($newRows) {
        foreach ($newRows as $k => $row) {
            $row['banker'] = implode('|', $row['banker']);
            $row['player'] = implode('|', $row['player']);
            $row['create_time'] = $this->formatDateTime($row['create_time']);

            $trxId = $row['create_trans_id'];
            $block_num = Eos::getRealBlockNum($trxId, Eos::getTempBlockNum($trxId));
            if ($block_num) {
                $row['create_block_num'] = $block_num;
            }

            $newRows[$k] = $row;
        }

        parent::addNewRows($newRows);

        foreach ($newRows as $row) {
            $eventData = [
                'old' => $this->objTable->getOne([
                    '_field' => 'id',
                    '_where' =>  "id<{$row['id']}",
                    '_sortKey' => 'id DESC',
                    '_limit' => 1,
                ]),

                'new' => $row['id'],
            ];
            Eos::pubEvent('baccarat:new_game', $eventData);
        }

    }

//    protected function updateDb($rows) {
//
//        parent::updateDb($rows);
//    }

    protected function updateRow($row, $priValue, $dbRow) {

        if ($row['game_state'] == Game::STATUS_PLAYING && in_array($dbRow['game_state'], [Game::STATUS_PLAYING, Game::STATUS_OPENING]) && $dbRow['create_block_num']) {
            return;
        }

        $row['banker'] = implode('|', $row['banker']);
        $row['player'] = implode('|', $row['player']);
        $row['create_time'] = $this->formatDateTime($row['create_time']);


        if (!$dbRow['create_block_num']) {
            $trxId = $row['create_trans_id'];
            $block_num = Eos::getRealBlockNum($trxId, Eos::getTempBlockNum($trxId));
            if ($block_num) {
                $row['create_block_num'] = $block_num;
            }
        }

        parent::updateRow($row, $priValue, $dbRow);

    }


}
