<?php

error_reporting (0);

require_once 'library/DateTime.php';
require_once('inbox/lib/php-imap-master/src/ImapMailbox.php');


class AccountInfo
{
    public $host;
    public $username;
    public $password;
    public $protocol;
    public $imapPath;

    public function __construct($host, $username, $password, $protocol)
    {
        $this->hostname = $host;
        $this->username = $username;
        $this->password = $password;
        $this->protocol = $protocol;
        $this->imapPath = '{' . $host . '/' . $protocol . '/ssl}INBOX';
    }
}

class Inbox_LoadHeadersController extends Inbox_Controller_Base
{
    protected $accountId;
    protected $subject;
    protected $from;
    protected $to;
    protected $date;
    protected $message_id;
    protected $size;
    protected $uid;
    protected $msgno;
    protected $recent;
    protected $flagged;
    protected $answered;
    protected $deleted;
    protected $seen;
    protected $draft;
    protected $udate;

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

    protected function getAccountInfo($accountId)
    {
        $select = $this->_dbAdapter
            ->select()
            ->from('ui_account')
            ->where('id = ' . $this->_dbAdapter->quote($accountId, 'INTEGER'));

        $accountRow = $this->_dbAdapter->fetchRow($select);

        return new AccountInfo($accountRow['serverAddress'], $accountRow['accountEmail'],
                               $accountRow['password'], $accountRow['protocol']);
    }

    protected function loadAccountHeaders($accountId)
    {
        try
        {
            $accountInfo = $this->getAccountInfo($accountId);

            $this->deleteUserHeaders($accountId);

            $imapPath = $accountInfo->imapPath;
            $username = $accountInfo->username;
            $password = $accountInfo->password;

            $attachmentDir = dirname(__FILE__) . '/attachments';

            $mailbox = new ImapMailbox($imapPath, $username, $password, $attachmentDir, 'utf-8');

            $mailsIds = $mailbox->searchAndSortMails('ALL');
            // $mailsIds = $mailbox->searchMailbox('UID 3');
            // $mailsIds = $mailbox->searchAndSortMails('UID "3:*"');

            if(!$mailsIds)
            {
                return true;
            }

            if (!empty($mailsIds))
            {
                // for every email...
                foreach($mailsIds as $mailId)
                {
                    // get header information
                    $mailsInfo = $mailbox->getMailsInfo(array($mailId));
                    $this->insertHeader($accountId, $mailsInfo[0]);
               }
            }
            return true;
        }
        catch (Exception $e)
        {
            return false;
        }
    }

    public function indexAction()
    {

        $params = $this->getRequest()->getParams();


        try
        {
            for ($accountId = 1; $accountId < 2; $accountId++)
            {
                $this->loadAccountHeaders($accountId);
            }

            $this->renderJson($this->_statusOK);
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }

    protected function populateParameters($accountId, $emailHeader)
    {
        $this->accountId =  $accountId;
        $this->subject =    $emailHeader->subject;
        $this->from =       $emailHeader->from;
        $this->to =         $emailHeader->to;
        $this->date =       $emailHeader->date;
        $this->message_id = $emailHeader->message_id;
        $this->size =       $emailHeader->size;
        $this->uid =        $emailHeader->uid;
        $this->msgno =      $emailHeader->msgno;
        $this->recent =     $emailHeader->recent;
        $this->flagged =    $emailHeader->flagged;
        $this->answered =   $emailHeader->answered;
        $this->deleted =    $emailHeader->deleted;
        $this->seen =       $emailHeader->seen;
        $this->draft =      $emailHeader->draft;
        $this->udate =      $emailHeader->udate;
    }


    protected function deleteUserHeaders($accountId)
    {
        try
        {
            $result = $this->_dbAdapter->delete('ui_emailheader', 'accountId = ' . $this->_dbAdapter->quote($accountId, 'INTEGER' ));
            return true;
        }
        catch (Exception $e)
        {
            return false;
        }
    }


    protected function insertHeader($accountId, $emailHeader)
    {
        try
        {
            $sql = <<<EOD
INSERT INTO ui_emailheader (
`accountId`,
`subject`,
`from`,
`to`,
`date`,
`message_id`,
`size`,
`uid`,
`msgno`,
`recent`,
`flagged`,
`answered`,
`deleted`,
`seen`,
`draft`,
`udate`
) VALUES (
:accountId,
:subject,
:from,
:to,
:date,
:message_id,
:size,
:uid,
:msgno,
:recent,
:flagged,
:answered,
:deleted,
:seen,
:draft,
:udate
);
EOD;

            $this->populateParameters($accountId, $emailHeader);

            $stmt = $this->_dbAdapter->prepare($sql);

            $stmt->bindParam('accountId',  $this->accountId);
            $stmt->bindParam('subject',    $this->subject);
            $stmt->bindParam('from',       $this->from);
            $stmt->bindParam('to',         $this->to);
            $stmt->bindParam('date',       $this->date);
            $stmt->bindParam('message_id', $this->message_id);
            $stmt->bindParam('size',       $this->size);
            $stmt->bindParam('uid',        $this->uid);
            $stmt->bindParam('msgno',      $this->msgno);
            $stmt->bindParam('recent',     $this->recent);
            $stmt->bindParam('flagged',    $this->flagged);
            $stmt->bindParam('answered',   $this->answered);
            $stmt->bindParam('deleted',    $this->deleted);
            $stmt->bindParam('seen',       $this->seen);
            $stmt->bindParam('draft',      $this->draft);
            $stmt->bindParam('udate',      $this->udate);

            $success = $stmt->execute();

            $id = $this->_dbAdapter->lastInsertId();

            //$select = $this->_dbAdapter
            //    ->select()
            //    ->from('ui_emailheader')
            //    ->where('id = ' . $this->_dbAdapter->quote($id, 'INTEGER'));
            //
            //$this->renderJson($this->_dbAdapter->fetchRow($select));
        }
        catch (Exception $e)
        {
            $this->renderJson(array('error' => array('text' => $e->getMessage())));
        }
    }

    public function getAction()
    {
        $params = $this->getRequest()->getParams();
        $this->methodNotAllowed();
    }

    public function postAction()
    {
        $this->methodNotAllowed();
    }

    public function putAction()
    {
        $this->methodNotAllowed();
    }

    public function deleteAction()
    {
        $this->methodNotAllowed();
    }
}
