<?php

namespace TdyGames\Table;

use TdyGames\Model;
use TdyCommons\Table\Table;
use TdyPlayers\Model\Player;
use Zend\Db\ResultSet\HydratingResultSet;
use Zend\Db\Sql\Delete;
use Zend\Db\Sql\Insert;
use Zend\Db\Sql\Predicate;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Sql;
use Zend\Db\Sql\Update;
use Zend\Db\Sql\Where;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;

/**
 * Class Mixtures
 *
 * @package TdyContests\Table
 *
 * @author  James Lloyd Atwil <james@nadows.com>
 */
class Mixtures extends Table
{

    /**
     * @var array
     */
    public $relatedTables = [];

    /**
     * @param array $relatedTables
     */
    public function setRelatedTables($relatedTables)
    {
        $this->relatedTables = $relatedTables;
    }

    /**
     * @param null|int $cn
     * @param null|int $pl
     * @param null|int $st
     * @param string   $q
     * @param array    $exclusion
     * @param array    $filters
     * @param array    $sort
     * @param bool     $paginated
     *
     * @return bool|HydratingResultSet|Paginator
     */
    public function fetch($cn = null, $pl = null, $st = null, $q = '', $exclusion = [], $filters = [], $sort = [], $paginated = false)
    {
        $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::fetch() start.');

        $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Contest : ' . $cn);
        $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Player  : ' . $pl);
        $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Slot    : ' . $st);

        $select = null;

        if (!is_null($cn) && !is_null($pl)) {
            $select = $this->buildQueryByContestAndPlayer($cn, $pl, $q, $exclusion, $filters, $sort, $paginated);
        } else if (!is_null($st)) {
            $select = $this->buildQueryBySlot($st, $q, $exclusion, $filters, $sort, $paginated);
        }

        $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'SQL Statement: ' . $select->getSqlString($this->getAdapter()->getPlatform()));

        $resultSet = new HydratingResultSet();
        $resultSet->setObjectPrototype(new Model\Mixture());

        if ($paginated) {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Is Paginable: YES');

            $paginatorAdapter = new DbSelect($select, $this->getTableGateway()->getSql(), $resultSet);
            $paginator        = new Paginator($paginatorAdapter);

            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Returns Paginator instance.');
            $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::fetch() end.');

            return $paginator;
        } else {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Is Paginable: NO');

            $sql       = new Sql($this->tableGateway->getAdapter());
            $statement = $sql->prepareStatementForSqlObject($select);

            $results = $statement->execute();
            $resultSet->initialize($results);

            if (!$resultSet) {
                $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Returns FALSE');
                $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::fetch() end.');

                return false;
            } else {
                $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Returns HydratingResultSet instance.');
                $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::fetch() end.');

                return $resultSet;
            }
        }
    }

    /**
     * Returns the Contest.
     *
     * @param int $id
     *
     * @return Model\Contest|null
     * @throws \Exception
     */
    public function get($id)
    {
        $rowset = $this->tableGateway->select([$this->columns['id'] => $id]);
        $row    = $rowset->current();
        if (!$row) {
            return null;
        }

        return $row;
    }

    /**
     * @param Model\Mixture $mixture
     *
     * @throws \Exception
     */
    public function save(Model\Mixture $mixture)
    {
        $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::save() start.');

        $data = [
            $this->columns['slot-id']        => $mixture->slotId,
            $this->columns['team-home']      => $mixture->teamHome,
            $this->columns['team-home-side'] => $mixture->teamHomeSide,
            $this->columns['team-away']      => $mixture->teamAway,
            $this->columns['team-away-side'] => $mixture->teamAwaySide,
            $this->columns['bet']            => $mixture->bet,
            $this->columns['score-home']     => $mixture->scoreHome,
            $this->columns['score-away']     => $mixture->scoreAway,
            $this->columns['points']         => $mixture->points,
        ];

        $id = (int) $mixture->id;
        if ($id == 0) {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Inserting Mixture record.');

            $data['is_active']  = 1;
            $data['created_by'] = $mixture->createdBy;
            $data['created_on'] = date('Y-m-d H:i:s');

            $insert = new Insert($this->getTableGateway()->getTable());
            $insert->values($data);

            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'SQL Statement: ' . $insert->getSqlString($this->getAdapter()->getPlatform()));

            $sql       = new Sql($this->tableGateway->getAdapter());
            $statement = $sql->prepareStatementForSqlObject($insert);

            $statement->execute();

            $id = $this->getAdapter()->getDriver()->getLastGeneratedValue();

            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Mixture ' . $id . ' has been inserted.');
            $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::save() end.');

            return $this->get($id);
        } else {
            if ($this->get($id)) {
                $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Updating Mixture record.');

                $data[$this->columns['updated-by']] = $mixture->updatedBy;
                $data[$this->columns['updated-on']] = date('Y-m-d H:i:s');

                $update = new Update($this->getTableGateway()->getTable());
                $update->set($data);
                $update->where([$this->columns['id'] => $id]);

                $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'SQL Statement: ' . $update->getSqlString($this->getAdapter()->getPlatform()));

                $sql       = new Sql($this->tableGateway->getAdapter());
                $statement = $sql->prepareStatementForSqlObject($update);

                $statement->execute();

                $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Mixture ' . $id . ' has been updated.');
                $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::save() end.');

                return $this->get($id);
            } else {
                $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Mixture ID ' . $id . ' does not exists. Update failed.');
                $this->getLogger()->debug($this->indent . 'Contests\Slots\Mixtures::save() end.');

                throw new \Exception('Contest ID does not exist');
            }
        }
    }

    /**
     * @param Model\Mixture $mixture
     *
     * @throws \Exception
     */
    public function delete(Model\Mixture $mixture)
    {
        $this->getLogger()->debug($this->indent . 'Mixtures::delete() start.');

        if ($this->get($mixture->id)) {
            $data = [
                $this->columns['is-active']  => 0,
                $this->columns['deleted-by'] => $mixture->deletedBy,
                $this->columns['deleted-on'] => date('Y-m-d H:i:s'),
            ];

            $update = new Update($this->getTableGateway()->getTable());
            $update->set($data);
            $update->where([$this->columns['id'] => $mixture->id]);

            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'SQL Statement: ' . $update->getSqlString($this->getAdapter()->getPlatform()));

            $sql       = new Sql($this->tableGateway->getAdapter());
            $statement = $sql->prepareStatementForSqlObject($update);

            $statement->execute();

            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Mixture ' . $mixture->id . ' has been deleted.');
            $this->getLogger()->debug($this->indent . 'Mixtures::delete() end.');

        } else {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Mixture ID ' . $mixture->id . ' does not exists. Deletion failed.');
            $this->getLogger()->debug($this->indent . 'Mixtures::delete() end.');

            throw new \Exception('Mixture ID does not exist');
        }
    }


    protected function buildQueryBySlot($sl, $q = '', $exclusion = [], $filters = [], $sort = [])
    {
        $select = new Select();
        $select->from($this->getTableGateway()->getTable());
        $conditions = [];

        $where = new Where([]);
        $where->addPredicate(new Predicate\Expression('slot_id = ?', $sl));
        $conditions[] = $where;

        $where = new Where([]);
        $where->addPredicate(new Predicate\Expression('is_active = ?', 1));
        $conditions[] = $where;

        if (!empty($q)) {
            //$where = new Where([], Predicate\PredicateSet::OP_OR);
            //$where->addPredicate(new Predicate\Like($this->columns['slug'], '%' . $q . '%'));
            //$where->addPredicate(new Predicate\Like($this->columns['name'], '%' . $q . '%'));
            //$conditions[] = $where;
        }

        if (!empty($filters)) {
            $where = new Where([]);
            foreach ($filters as $k => $v) {
                if (is_array($v)) {
                    $where->addPredicate(new Predicate\In($k, $v));
                } else {
                    $where->addPredicate(new Predicate\Expression($k . ' = ?', $v));
                }
            }
            $conditions[] = $where;
        }

        if (!empty($exclusion)) {
            $where = new Where([]);
            $where->addPredicate(new Predicate\NotIn('id', $exclusion));
            $conditions[] = $where;
        }

        $select->where($conditions, Predicate\PredicateSet::OP_AND);

        if (!is_null($sort)) {
            if ($this->isSortEmpty($sort)) {
                $select->order([
                    $this->columns['id'] => 'DESC',
                ]);
            } else {
                $select->order($sort);
            }
        } else {
            $select->order($sort);
        }

        return $select;
    }

    protected function buildQueryByContestAndPlayer($cn, $pl, $q = '', $exclusion = [], $filters = [], $sort = [])
    {
        $select = new Select();
        $select->from(['mx' => $this->getTableGateway()->getTable()]);
        $select->join(['sl' => $this->relatedTables['contests_slots']['name']], 'mx.slot_id = sl.id', [], Select::JOIN_LEFT);
        $conditions = [];

        $where = new Where([]);
        $where->addPredicate(new Predicate\Expression('sl.contest_id = ?', $cn));
        $where->addPredicate(new Predicate\Expression('sl.player_id = ?', $pl));
        $conditions[] = $where;

        $where = new Where([]);
        $where->addPredicate(new Predicate\Expression('mx.is_active = ?', 1));
        $conditions[] = $where;

        if (!empty($q)) {
            //$where = new Where([], Predicate\PredicateSet::OP_OR);
            //$where->addPredicate(new Predicate\Like($this->columns['slug'], '%' . $q . '%'));
            //$where->addPredicate(new Predicate\Like($this->columns['name'], '%' . $q . '%'));
            //$conditions[] = $where;
        }

        if (!empty($filters)) {
            $where = new Where([]);
            foreach ($filters as $k => $v) {
                if (is_array($v)) {
                    $where->addPredicate(new Predicate\In($k, $v));
                } else {
                    $where->addPredicate(new Predicate\Expression($k . ' = ?', $v));
                }
            }
            $conditions[] = $where;
        }

        if (!empty($exclusion)) {
            $where = new Where([]);
            $where->addPredicate(new Predicate\NotIn('id', $exclusion));
            $conditions[] = $where;
        }

        $select->where($conditions, Predicate\PredicateSet::OP_AND);

        if (!is_null($sort)) {
            if ($this->isSortEmpty($sort)) {
                $select->order([
                    $this->columns['id'] => 'ASC',
                ]);
            } else {
                $select->order($sort);
            }
        } else {
            $select->order($sort);
        }

        return $select;
    }

}
