<?php

class Inbox_Controller_Base extends Atmail_Controller_Base
{
    protected $_dbAdapter;
    protected $_restParameters;

    protected $_columns;
    protected $_table;

    protected $_isAuthenticated = false;
    protected $_Account = '';
    protected $_inputJsonArray = array();
    
    // HTTP response headers will be one of the following:
    const STATUS_CODE_CONTINUE = 100; // 100 Continue
    const STATUS_CODE_OK = 200; // 200 OK
    const STATUS_CODE_CREATED = 201; // 201 Created
    const STATUS_CODE_ACCEPTED = 202; // 202 Accepted
    const STATUS_CODE_NO_CONTENT = 204; // 204 No Content
    const STATUS_CODE_NOT_MODIFIED = 304; // 304 Not Modified
    const STATUS_CODE_BAD_REQUEST = 400; // 400 Bad Request
    const STATUS_CODE_AUTHORIZATION_REQUIRED = 401; // 401 Authorization required
    const STATUS_CODE_FORBIDDEN = 403; // 403 Forbidden
    const STATUS_CODE_NOT_FOUND = 404; // 404 Not Found
    const STATUS_CODE_METHOD_NOT_ALLOWED = 405; // 405 Method Not Allowed
    const STATUS_CODE_PRECONDITION_FAILED = 412; // 412 Precondition Failed
    const STATUS_CODE_INTERNAL_SERVER_ERROR = 500; // 500 Internal Server Error
    const STATUS_CODE_NOT_IMPLEMENTED = 501; // 501 Not Implemented

    public function init()
    {
        parent::init();

        $this->_restParameters = array();

        // Load the system settings
        $this->_globalConfig = Zend_Registry::get('config')->global;

        $this->_dbAdapter = Zend_Registry::get('dbAdapter');

        $this->_notFound = array('status' => 'NOT_FOUND');
        $this->_noResults = array('status' => 'NO_RESULTS');
        $this->_zeroResults = array('status' => 'ZERO_RESULTS');
        $this->_methodNotAllowed = array('status' => 'METHOD_NOT_ALLOWED');
        $this->_preconditionFailed = array('status' => 'PRECONDITION_FAILED');
        $this->_authorizationRequired = array('status' => 'AUTHORIZATION_REQUIRED');
        $this->_statusOK = array('status' => 'OK');

        if (!Atmail_FormAuth::authenticated())
        {
            $this->_isAuthenticated = false;
        }
        else
        {
            $this->_isAuthenticated = true;

            $userData = Zend_Auth::getInstance()->getStorage()->read();
            $this->_Account = $userData['Account'];

            $this->fileAdapter = Atmail_Files_Factory::instance($this->_Account);
        }
    }

    protected function getTableName()
    {
        return $this->_table;
    }

    protected function &getTableColumns()
    {
        return $this->_columns;
    }

    protected function isAuthenticated()
    {
        if (!$this->_isAuthenticated)
        {
            $this->getResponse()->setHttpResponseCode(self::STATUS_CODE_AUTHORIZATION_REQUIRED);
            $this->renderJson($this->_authorizationRequired);
        }
        return $this->_isAuthenticated;
    }

    protected function methodNotAllowed()
    {
        $this->getResponse()->setHttpResponseCode(self::STATUS_CODE_METHOD_NOT_ALLOWED);
        $this->renderJson($this->_methodNotAllowed);
    }

    protected function preconditionFailed()
    {
        $this->getResponse()->setHttpResponseCode(self::STATUS_CODE_PRECONDITION_FAILED);
        $this->renderJson($this->_preconditionFailed);
    }

    protected function notFound()
    {
        $this->getResponse()->setHttpResponseCode(self::STATUS_CODE_NOT_FOUND);
        $this->renderJson($this->_notFound);
    }

    protected function renderJsonError($msg)
    {
        $this->renderJson(array("error" => array("text" => "{$msg}")));
    }

    protected function getUpdateStatement()
    {
        $updateStatement = "UPDATE {$this->getTableName()} SET ";

        $firstColumn = true;
        foreach ($this->_restParameters as $key => $val)
        {
            $updateStatement .= ($firstColumn ? '' : ', ') . "`$key` =  :$key ";

            if ($firstColumn)
            {
                $firstColumn = false;
            }
        }

        $updateStatement .= ' WHERE id=:id';

        return $updateStatement;
    }

    protected function getInsertStatement()
    {
        $sqlTemplate = "INSERT INTO {$this->getTableName()} (`%s`) VALUES (:%s)";
        $cols = array();

        foreach ($this->_columns as $key => $val)
        {
            if($key != 'id'){
                array_push($cols, $key);
            }
        }

        return sprintf($sqlTemplate, join('`,`', $cols), join(',:', $cols));
    }

    protected function isJson()
    {
        $contentType = $this->getRequest()->getHeader('Content-Type');

        if (empty($contentType) || (!empty($contentType) && strcasecmp($contentType, 'application/x-www-form-urlencoded') != 0))
        {
            return true;
        }

        return false;
    }

    protected function getJsonParam($jsonArray, $key, $default = null)
    {
        $key = (string)$key;
        if (isset($jsonArray[$key]))
        {
            return $jsonArray[$key];
        }

        return $default;
    }

    protected function populateParameters()
    {
        if ($this->isJson())
        {
            $inputJson = file_get_contents('php://input');
            $this->_inputJsonArray = json_decode($inputJson, TRUE);

            if ($this->_inputJsonArray != null)
            {
                foreach ($this->_inputJsonArray as $key => $val)
                {
                    if (array_key_exists($key, $this->_columns))
                    {
                        $this->_restParameters[$key] = $val;
                        $this->_columns[$key] = $val;
                    }
                }
            }
        }
        else
        {
            foreach ($_POST as $key => $val)
            {
                if (array_key_exists($key, $this->_columns))
                {
                    $this->_restParameters[$key] = $val;
                    $this->_columns[$key] = $val;
                }
            }
        }
    }
}
