<?php

namespace TdySports\Table;

use TdySports\Model;
use TdyCommons\Table\Table;
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 Weeks
 *
 * @package TdySports\Table
 *
 * @author  James Lloyd Atwil <james@nadows.com>
 */
class Weeks 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 . 'Weeks::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['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);
        }

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

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

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

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

                return $resultSet;
            }
        }
    }

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

        return $row;
    }

    /**
     * @param $seasonId
     * @param $slug
     *
     * @return Model\Week|null
     */
    public function getBySlug($seasonId, $slug)
    {
        $rowset = $this->tableGateway->select([$this->columns['slug'] => $slug, $this->columns['season-id'] => $seasonId]);
        /** @var Model\Week $row */
        $row = $rowset->current();
        if (!$row) {
            return null;
        }

        return $row;
    }

    /**
     * @return null|Model\Week
     */
    public function getCurrentWeek()
    {
        $rowset = $this->tableGateway->select([$this->columns['is-current'] => 1]);

        /** @var Model\Week $row */
        $row = $rowset->current();

        if (!$row) {
            return null;
        }

        return $row;
    }

    /**
     * @return null|Model\Week
     */
    public function getNextWeek()
    {
        $currentWeek = $this->getCurrentWeek();

        $rowset = $this->tableGateway->select([$this->columns['number'] => $currentWeek->number + 1]);

        /** @var Model\Week $row */
        $row = $rowset->current();

        if (!$row) {
            return null;
        }

        return $row;
    }

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

        $data = [
            $this->columns['slug']      => $week->slug,
            $this->columns['sport-id']  => $week->sportId,
            $this->columns['league-id'] => $week->leagueId,
            $this->columns['season-id'] => $week->seasonId,
            $this->columns['number']    => $week->number,
            $this->columns['name']      => $week->name,
        ];

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

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

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

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

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

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

    /**
     * Removes the is_current flag.
     */
    public function decurrent()
    {
        $this->getLogger()->debug($this->indent . 'Weeks::decurrent() start.');

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

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

        $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 . 'Week has been decurrented.');
        $this->getLogger()->debug($this->indent . 'Weeks::decurrent() end.');

    }

    public function declareNewWeek()
    {
        $this->getLogger()->debug($this->indent . 'Weeks::declareNewWeek() start.');
        $nextWeek            = $this->getNextWeek();
        $nextWeek->isCurrent = 1;

        $this->decurrent();
        $this->save($nextWeek);
        $this->getLogger()->debug($this->indent . 'Weeks::declareNewWeek() end.');
    }

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

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

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

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

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

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

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

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

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

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

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

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

    }

}
