<?php

/**
 * 事件逻辑
 */

namespace Game\Logic;

use Framework\Log\LogMark;
use Framework\MVC\ModelManager;
use Game\Constant\GameErrorCode;
use Game\Model\EventModel;
use Game\Constant\ModelTypeDefine;

trait EventLogic
{
    public function triggerEvent(int $eventId, array $param, bool $isSend = true)
    {
        // 查找事件
        /**
         * @var EventModel $eventModel
         */
        $eventModel = ModelManager::getInstance()->getModel(ModelTypeDefine::EVENT);
        $this->dealEvents($eventId, $param, $eventModel, $isSend);
    }

    public function removeEvent(int $eventId, array $data)
    {
        /**
         * @var EventModel $eventModel
         */
        $eventModel = ModelManager::getInstance()->getModel(ModelTypeDefine::EVENT);
        $eventModel->removeEvent($eventId, $data);
    }

    //触发对方事件
    public function triggerTargetEvent(int $eventId, array $param, int $targetPlayerId)
    {
        ModelManager::getInstance()->setPlayerId($targetPlayerId);
        /**
         * @var EventModel $eventModel
         */
        $eventModel = ModelManager::getInstance()->getModel(ModelTypeDefine::EVENT);
        $eventModel->setPlayerId($targetPlayerId);
        $this->dealEvents($eventId, $param, $eventModel, false);
    }

    //处理事件
    private function dealEvents(int $eventId, array $param, EventModel $eventModel, bool $isSend = true)
    {
        $events = $eventModel->getEventByEventId($eventId);
        if (empty($events)) {
            return;
        }
        //整理 按model分别处理
        $tmpModel = array();
        foreach ($events as $key => $value) {
            $tmp = explode("-", $key);
            if (count($tmp) != 2) {
                LogMark::getInstance()->markDebug(
                    "[EventLogic] triggerEvent data error",
                    $events
                );
                //删除
                $eventModel->removeEvent($eventId, array($key));
                continue;
            }
            $model = intval($tmp[0]);
            $id = intval($tmp[1]);
            $tmpModel[$model][] = $id;
        }
        foreach ($tmpModel as $modelName => $ids) {
            $model = ModelManager::getInstance()->getModel($modelName);
            if (is_null($model)) {
                LogMark::getInstance()->markError(
                    GameErrorCode::EVENT_TRIGGER_MODEL_NOT_FOUND,
                    "[EventLogic] trigger model not found",
                    array(
                        "modelId" => $model
                    )
                );
                continue;
            }
            if (method_exists($model, "trigger")) {
                $model->trigger($ids, $param, $isSend);
            }
        }
    }
}