<?php

namespace TdyPlayers\Table;

use TdyPlayers\Model;
use TdyCommons\Table\Table;
use Zend\Crypt\Password\Bcrypt;
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 Players
 *
 * @package TdyPlayers\Table
 *
 * @author  James Lloyd Atwil <james@nadows.com>
 */
class Players extends Table
{

    /**
     * @param string $q
     * @param array  $exclusion
     * @param array  $filters
     * @param array  $sort
     * @param bool   $paginated
     *
     * @return bool|HydratingResultSet|Paginator
     */
    public function fetch($q = '', $exclusion = [], $filters = [], $sort = [], $paginated = false)
    {
        $this->getLogger()->debug($this->indent . 'Players::fetch() start.');

        $select = new Select();
        $select->from($this->getTableGateway()->getTable());
        $conditions = [];

        $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['first-name'], '%' . $q . '%'));
            $where->addPredicate(new Predicate\Like($this->columns['last-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('last_name ASC, first_name ASC');
            } else {
                $select->order($sort);
            }
        } else {
            $select->order($sort);
        }

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

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

        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 . 'Players::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 . 'Players::fetch() end.');

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

                return $resultSet;
            }
        }
    }

    /**
     * Returns the Player.
     *
     * @param int $id
     *
     * @return Model\Player|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 string $name
     * @param int    $exclude
     *
     * @return Model\Player|bool|null
     */
    public function getByUsername($name, $exclude = 0)
    {
        $rowset = $this->tableGateway->select(function (Select $select) use ($name, $exclude) {
            $select->where(["username = '" . $name . "'"]);
            $select->where(["is_active = 1"]);
            if ($exclude > 0) {
                $select->where(["id != '" . $exclude . "'"]);
            }
        });
        $row    = $rowset->current();
        if (!$row) {
            return false;
        }

        return $row;
    }

    /**
     * @param string $email
     * @param int    $exclude
     *
     * @return Model\Player|bool|null
     */
    public function getByEmail($email, $exclude = 0)
    {
        $rowset = $this->tableGateway->select(function (Select $select) use ($email, $exclude) {
            $select->where(['email' => $email]);
            $select->where(['is_active' => 1]);
            if ($exclude > 0) {
                $select->where(["id != '" . $exclude . "'"]);
            }
        });
        $row    = $rowset->current();
        if (!$row) {
            return false;
        }

        return $row;
    }

    /**
     * @param Model\Player $player
     *
     * @return Model\Player
     * @throws \Exception
     */
    public function save(Model\Player $player)
    {
        $this->getLogger()->debug($this->indent . 'Players::save() start.');

        $data = [
            $this->columns['username']    => $player->username,
            $this->columns['last-name']   => $player->lastName,
            $this->columns['first-name']  => $player->firstName,
            $this->columns['middle-name'] => $player->middleName,
            $this->columns['suffix']      => $player->suffix,
            $this->columns['nickname']    => $player->nickname,
            $this->columns['email']       => $player->email,
            $this->columns['birthdate']   => $player->birthdate instanceof \DateTime ? $player->birthdate->format('Y-m-d') : null,
        ];

        if ($player->password != '' && !is_null($player->password)) {
            $bcrypt                           = new Bcrypt();
            $data[$this->columns['password']] = $bcrypt->create($player->password);
        }

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

            $data['is_active']  = 1;
            $data['created_by'] = $player->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 . 'Player ' . $id . ' has been inserted.');
            $this->getLogger()->debug($this->indent . 'Players::save() end.');

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

                $data[$this->columns['updated-by']] = $player->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 . 'Player ' . $id . ' has been updated.');
                $this->getLogger()->debug($this->indent . 'Players::save() end.');

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

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

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

        if ($this->get($player->id)) {
            $data = [
                $this->columns['is-active']  => 0,
                $this->columns['deleted-by'] => $player->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'] => $player->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 . 'Player ' . $player->id . ' has been deleted.');
            $this->getLogger()->debug($this->indent . 'Players::delete() end.');

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

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

    /**
     * Restore Player to the table. Sets the Player to active.
     *
     * @param Model\Player $player
     *
     * @throws \Exception
     */
    public function restore(Model\Player $player)
    {
        $this->getLogger()->debug($this->indent . 'Players::restore() start.');

        if ($this->get($player->id)) {
            $data = [
                $this->columns['is-active']  => 1,
                $this->columns['updated-by'] => $player->updatedBy,
                $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'] => $player->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 . 'Player ' . $player->id . ' has been restored.');
            $this->getLogger()->debug($this->indent . 'Players::restore() end.');

        } else {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Player ID ' . $player->id . ' does not exists. Restoration failed.');
            $this->getLogger()->debug($this->indent . 'Players::restore() end.');

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

    /**
     * Set a new password and save to the table.
     *
     * @param Model\Player $player
     *
     * @throws \Exception
     */
    public function resetPassword(Model\Player $player)
    {
        $this->getLogger()->debug($this->indent . 'Players::resetPassword() start.');

        if ($this->get($player->id)) {
            $data = [
                $this->columns['password']   => $player->password,
                $this->columns['updated-by'] => $player->updatedBy,
                $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'] => $player->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 . 'Password of the Player ' . $player->id . ' has been reset.');
            $this->getLogger()->debug($this->indent . 'Players::resetPassword() end.');

        } else {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Player ID ' . $player->id . ' does not exists. Password reset failed.');
            $this->getLogger()->debug($this->indent . 'Players::resetPassword() end.');

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

    /**
     * Permanently delete the Player.
     *
     * @param Model\Player $player
     *
     * @throws \Exception
     */
    public function purge(Model\Player $player)
    {
        $this->getLogger()->debug($this->indent . 'Players::purge() start.');

        if ($this->get($player->id)) {
            $update = new Delete($this->getTableGateway()->getTable());
            $update->where([$this->columns['id'] => $player->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 . 'Player ' . $player->id . ' has been purged, as in permanently deleted.');
            $this->getLogger()->debug($this->indent . 'Players::purge() end.');

        } else {
            $this->getLogger()->debug($this->indent . self::LOGGER_INDENT . 'Player ID ' . $player->id . ' does not exists. Purge failed.');
            $this->getLogger()->debug($this->indent . 'Players::purge() end.');

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

    }

}
