<?php

// todo:dtb test class
class MonkeyClass
{
    // property declaration
    public $var = 'a default value';
    public $varint = 1;
    public $varfloat = 1.9;

    private $hiddenvar = 'hidden';

    // method declaration
    public function displayVar() {
        echo $this->var;
    }
}

class Inbox_ImapController extends Atmail_Controller_Base
{
    protected $_dbTables;
    protected $_dbAdapter;

    // http://atmail.local/index.php/api/inbox2/view/id/1/GroupID/1
    public function init()
    {
        //TODO: extend authentication to support multiple user levels/roles/groups
        require_once 'application/models/api.php';
        $this->api = new api();

        $this->view->baseUrl = $this->_request->getBaseUrl();
        $this->view->appBaseUrl = $this->_request->getBaseUrl() . (strpos($this->_request->getBaseUrl(),'index.php')?'':'/index.php');
        $this->view->siteBaseUrl = Zend_Registry::get('siteBaseUrl');
        $this->view->moduleBaseUrl = $this->view->appBaseUrl . ($this->_request->module == 'default'?'':'/' . $this->_request->module);

        $this->_helper->viewRenderer->setNoRender();

        // Load all the params
        $this->requestParams = $this->getRequest()->getParams();

        // Use Cookie auth
        // if ( !Atmail_FormAuth::authenticated() )
        // {
        //    return $this->_forward('timeout', 'mail', 'api', $this->requestParams);
        // }

        //$this->userData = Zend_Auth::getInstance()->getStorage()->read();
        //$this->userData = Atmail_Password::processUser($this->userData);

        // Load the session
        $this->session = new Zend_Session_Namespace(ATMAIL_NAMESPACE);

        // Load the contacts class
        // $this->_contacts = new contacts( array('Account' => $this->userData['Account']) );
        $this->_contacts = new contacts( array('admin' => true) );

        // Find the users settings ( used for theme )
        // $this->view->UserSettings = Zend_Registry::get('UserSettings');

        // Used to determine the contact in the global addressbook
        // $this->view->Account = $this->userData['Account'];

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

        $this->_dbTables = new dbTables();
        $this->_dbAdapter = Zend_Registry::get('dbAdapter');
    }

// =======================================================================================================

    public function emailAttachmentAction()
    {
        // GET request for attachments
        // /$charter-user/$account/email-attatchment/$uid
        // 
        // API JSON response: responds with attachment download

        $resultList = array();

        $params = $this->getRequest()->getParams();
        array_push($resultList, $params);

        $id    = array_key_exists('page',    $params) ? $params['id']    : '1';

        $header1 = array(
            'attachment' => 'integer',
            );

        array_push($resultList, $header1);

        $this->renderJson($resultList);
    }

    public function emailBodyAction()
    {
        // GET request for email body:
        // /$charter-user/$account/email-body/$uid
        // 
        // API JSON response:
        // [
        //   {
        //     'full_headers': ['string'],
        //     'body': {
        //        'text':'string',
        //        'html':'string'
        //     },
        //     'attachments': [
        //        {
        //        'uid':'integer',
        //        'name':'string'
        //        },
        //     ...
        //     ]
        // ]

        $resultList = array();

        $params = $this->getRequest()->getParams();
        array_push($resultList, $params);

        $user    = array_key_exists('user',    $params) ? $params['user']    : 'default';
        $account = array_key_exists('account', $params) ? $params['account'] : 'default';
        $id      = array_key_exists('id',      $params) ? $params['id']      : '1';

        $emailBody = array(
            'full_headers' => array('x' => 'string1', 'y' => 'string1'),
            'body_text' => array(
                'text' => 'string',
                'html' => 'string'
                ),

            'attachments' => array(
                array(
                    array( 'uid' => '1', 'name' => 'string'),
                    array( 'uid' => '2', 'name' => 'string')
                    )
                )
            );

        array_push($resultList, $emailBody);

        $this->renderJson($resultList);
    }

    public function emailHeadersAction()
    {
        // GET request for email headers:
        // /$charter-user/$account/email-headers/$page
        //
        // API JSON response:
        //  [
        //   {
        //     'UID':'integer',
        //     'flags':'string',          // currently: Seen, Flagged and Replied. Is this IMAP standard?
        //     'priority':'string',       // We do not do anything with this currently, is it in the requirements?
        //     'msgPreview':'string',
        //     'to':'string',             // full formatted email address, e.g. "Bryon Bean" <bryon.bean@charter.net<mailto:bryon.bean@charter.net>>
        //     'to_name':'string',        // name portion of the email address, e.g. "Bryon Bean" (currently in response, but not necessary in my opinion)
        //     'to_email':'string',       // email portion of the email address, e.g. bryon.bean@charter.com<mailto:bryon.bean@charter.com>  (currently in response, but not necessary in my opinion)
        //     'from':'string',           // full formatted email address of the originator
        //     'from_name':'string',      //  (currently in response, but not necessary in my opinion)
        //     'from_email':'string',     //  (currently in response, but not necessary in my opinion)
        //     'recipients': ['string'],  // list of email addresses cc'd
        //     'subject':'string',
        //     'date':'integer',          // seconds since epoch
        //     'size':'integer',          // in bytes
        //   },
        // ...
        // ];

        $resultList = array();

        $params = $this->getRequest()->getParams();
        array_push($resultList, $params);

        $user    = array_key_exists('user',    $params) ? $params['user']    : 'default';
        $account = array_key_exists('account', $params) ? $params['account'] : 'default';
        $page    = array_key_exists('page',    $params) ? $params['page']    : '1';

        $header1 = array(
            'UID' => 'integer',
            'flags' => 'string',              // currently: Seen, Flagged and Replied. Is this IMAP standard?
            'priority' => 'string',           // We do not do anything with this currently, is it in the requirements?
            'msgPreview' => 'string',
            'to' => 'string',                 // full formatted email address, e.g. "Bryon Bean" <bryon.bean@charter.net<mailto:bryon.bean@charter.net>>
            'to_name' => 'string',            // name portion of the email address, e.g. "Bryon Bean" (currently in response, but not necessary in my opinion)
            'to_email' => 'string',           // email portion of the email address, e.g. bryon.bean@charter.com<mailto:bryon.bean@charter.com>  (currently in response, but not necessary in my opinion)
            'from' => 'string',               // full formatted email address of the originator
            'from_name' => 'string',          //  (currently in response, but not necessary in my opinion)
            'from_email' => 'string',         //  (currently in response, but not necessary in my opinion)
            'recipients' =>  array('string'), // list of email addresses cc'd
            'subject' => 'string',
            'date' => 'integer',              // seconds since epoch
            'size' => 'integer'               // in bytes
            );

        array_push($resultList, $header1);

        $this->renderJson($resultList);
    }

    public function accountsAction()
    {
        $resultList = array();

        $params = $this->getRequest()->getParams();
        array_push($resultList, $params);

        $account1 = array( 'id' => '1',
                           'serverAddress' => '',
                           'replyAddress' => '',
                           'accountEmail' => '',
                           'accountName' => '',
                           'signature' => '',
                           'realName' => '',
                           'protocol' => 'IMAP',
                           'password' => '',
                           'nickname' => '',
                           'capacity' => 1,
                           'primary' => false,
                           'quota' => 0.0,
                           'port' => 993
                           );

        $account2 = array( 'id' => '2',
                           'serverAddress' => '',
                           'replyAddress' => '',
                           'accountEmail' => '',
                           'accountName' => '',
                           'signature' => '',
                           'realName' => '',
                           'protocol' => 'IMAP',
                           'password' => '',
                           'nickname' => '',
                           'capacity' => 1,
                           'primary' => false,
                           'quota' => 0.0,
                           'port' => 993
                           );

//        array_push($resultList, $account1);
//        array_push($resultList, $account2);
//        $monkey = new MonkeyClass();
//        array_push($resultList, $monkey);

        $accountWhereClause = '';
        if (isset($account))
        {
            $accountWhereClause = "where account='$account'";
        }

        $q = "SELECT * from ui_account $accountWhereClause";
        Zend_Registry::get('log')->debug( __METHOD__ . ' #' . __LINE__ . ': $q=' . $q);

        $accounts = $this->_dbAdapter->fetchAll($q);

        array_push($resultList, $accounts);

        $this->renderJson($resultList);
        // $this->renderJson($accounts);
    }


// =======================================================================================================

    public function indexAction()
    {
        // $this->restserver->handle( array('method' => 'index') );
    }

    public function updateAction()
    {
        $params = $this->getRequest()->getParams();
        unset($params['api']);
        unset($params['module']);
        unset($params['controller']);
        unset($params['action']);

        $id = isset( $params['id'] )? $params['id'] : NULL;
        $groupId = $params['groupId'];

        unset($params['groupId']);

        //TODO: do fields check
        try
        {
            if (!$id)
            {
                $contact = array(
                    'contact' => $params,
                );

                $id = $this->_contacts->addContact($contact);

                if ($groupId)
                {

                    $this->_contacts->addContactToGroup(
                        array(
                            'id' => $id,
                            'GroupID' => $groupId,
                        )
                    );
                }
            }
            else
            {
                $contact = $params;
                $this->_contacts->updateContact($contact);
            }

            $contact = $this->_contacts->getContact($id, $groupId);

            $this->renderJson( $contact );
        }
        catch(Atmail_Exception $e)
        {
            $this->renderFail($e);
        }
    }


    public function createAction()
    {
        $params = $this->getRequest()->getParams();

        $stuffList = array('method' => 'index');
        $resultList = array_merge($stuffList, $params);
        $this->renderJson($resultList);



        //$params['method'] = 'domainCreate';
        //$this->restserver->handle($params);
    }

    public function listAction()
    {
        $this->_contacts->sharedAbookEnabled = true;

        // TODO: Implement filter class, ask the server for only XYZ fields ( not all, reduce JSON packet )
        $contactsAll = $this->_contacts->getContacts($this->requestParams);

        // Add the API call to fetch the last message for the contact
        if (isset($this->requestParams['LastMessage']))
        {
            $contactsFilter = array();
            $i = 0;

            foreach ($contactsAll as $contact)
            {
                $contactsAll[$i]['LastMessage'] = "Last message $i";
                $i++;
            }
        }

        if (isset($this->requestParams['Fields']) && is_array($this->requestParams['Fields']))
        {
            $contactsFilter = array();
            $i = 0;

            foreach ($contactsAll as $contact)
            {
                foreach ($this->requestParams['Fields'] as $field)
                {
                    if (isset($contact[$field]))
                    {
                        $contactsFilter[$i][$field] = $contact[$field];
                    }
                    else
                    {
                        $contactsFilter[$i][$field] = 'null';
                    }
                }

                $i++;
            }

            // Export a filtered contact list
            $resultList = $contactsFilter;
        }
        else
        {
            // Export all contacts
            $resultList = $contactsAll;
        }

        for ($i=0; $i<count($resultList); ++$i)
        {
            $resultList[$i]['isMyProfile'] = $resultList[$i]['Global'] == '1' && $resultList[$i]['Account'] == $this->userData['Account']? '1' : '0';
        }

        $this->renderJson($resultList);
    }

    public function deleteAction()
    {
        $param = $this->getRequest()->getParams();

        $ids = $param['id'];
        if (!is_array($ids))
        {
            $ids = array( $ids );
        }

        try
        {
            foreach ($ids as $id)
            {
                $param['id'] = $id;
                $this->_contacts->deleteContact($param);
            }
            $this->renderSuccess();
        }
        catch(Atmail_Exception $e)
        {
            $this->renderFail($e);
        }
    }

    public function deletefromgroupAction()
    {
        $requestParams = $this->getRequest()->getParams();
        // Loop for each element selected to delete

        if (!is_array($requestParams['id']))
        {
            $requestParams['id'] = array($requestParams['id']);
        }

        foreach($requestParams['id'] as $id)
        {
            $response = $this->_contacts->deleteContactGroup(array('id' => $id, 'GroupID' => $requestParams['GroupID']));
        }

        $this->renderSuccess();
    }

    public function viewAction()
    {
        $this->_contacts->sharedAbookEnabled = true;

        $contact = $this->_contacts->getContact($this->requestParams['id'], $this->requestParams['GroupID']);
        $this->renderJson($contact);
    }

    public function addtogroupAction()
    {
        $requestParams = $this->getRequest()->getParams();
        $status = 1;

        if (!is_array($requestParams['id']))
        {
            $requestParams['id'] = array($requestParams['id']);
        }

        if ($requestParams['GroupID'] < 0 && ($requestParams['GroupID'] != GROUP_SHARED && $requestParams['GroupID'] != GROUP_FAV))
        {
            $this->renderJson(array(
                'result' => 'failed',
                'error' => $this->view->translate('You are not allow to drop contacts to that folder.')
            ));

            return;
        }

        foreach($requestParams['id'] as $id)
        {
            if ($requestParams['GroupID'] == GROUP_SHARED)
            {
                //shared contact, update
                $this->_contacts->updateContact(array('Shared' => 1, 'id' => $id));
            }
            else if ($requestParams['GroupID'] == GROUP_FAV)
            {
                // 'add' the contact to the favourite group by flagging it as such
                $this->_contacts->updateContact(array('Favourite' => 1, 'id' => $id));
            }
            else
            {
                $groupIDs = $this->_contacts->getGroupIdsFromAbookId(array('id' => $id));

                $found = false;
                foreach($groupIDs as $groupID)
                {
                    if ($groupID['GroupID'] == GROUP_AUTO)
                    {
                        $found = true;
                        break;
                    }
                }

                if ($found)
                {
                    // remove the contact from the auto group
                    $response = $this->_contacts->deleteContactGroup(array('id' => $id, 'GroupID' => GROUP_AUTO));
                    jQuery('.address_row[contactid=' . $id . ']')->remove();
                }

                $status = $this->_contacts->addContactToGroup(array('GroupID' => $requestParams['GroupID'], 'id' => $id));
                $this->_contacts->updateContact(array('Shared' => 0, 'id' => $id));
            }
        }

        // If the contact was successfully added (Without a duplicate, update the count)
        if ($status == 1)
        {
        }

        $this->renderSuccess();
    }
}
