<?php


class Ibiscode_LoginAutoComplete extends Atmail_Controller_Plugin
{
    private $loginPage = false;
    
    private $_config;
    
    public function __construct()
    {   
        if (file_exists(dirname(__FILE__) . '/LoginAutoComplete/config.ini')) {
            $this->_config = new Zend_Config_Ini(dirname(__FILE__) . '/LoginAutoComplete/config.ini', 'main');
        }
        $this->_pluginName   = 'ImapPort';
        $this->_pluginCompany = 'Ibiscode';
        $this->_pluginAuthor = 'Brad Kowalczyk <brad@staff.atmail.com>';
        $this->_pluginDescription = 'Inserts default values for the login page';
        $this->_pluginCopyright = 'Brad Kowalczyk';
        $this->_pluginUrl = '';
        $this->_pluginNotes = '';
    }
    
    public function dispatchLoopStartup()
    {
        $request = $this->getRequest();
        if (($request->getControllerName() == 'index' && $request->getActionName() == 'index') ||
            ($request->getControllerName() == 'auth' && $request->getActionName() == 'logout')) {
            $this->_loginPage = true;
        }
    }
    
    public function postDispatch(Zend_Controller_Request_Abstract $request)
    {
        if ($this->_loginPage && $this->_config instanceof Zend_Config_Ini) {
            $page = $this->getResponse()->getBody();

            $page = str_replace('<input id="username" class="input" name="emailName" type="text" value="demo" />',
                                "<input id=\"username\" class=\"input\" name=\"emailName\" type=\"text\" value=\"{$this->_config->username}\" />", 
                                $page);
                                
            $page = preg_replace('/(<input id="pop3host" .+?)value="(.*?)"(.*?)\/>/',
                                "\$1 value=\"{$this->_config->domain}\" \$3/>",
                                $page);
                                
            $page = str_replace('<input id="password" class="input" name="password" type="password" value="demo" />',
                                "<input id=\"password\" class=\"input\" name=\"password\" type=\"password\" value=\"{$this->_config->password}\" />",
                                $page);
             
            $page = str_replace('<input id="Mailserverinput" class="input" name="requestedServer" type="text" value="demo.atmail.com" />',
                                "<input id=\"Mailserverinput\" class=\"input\" name=\"requestedServer\" type=\"text\" value=\"{$this->_config->mailserver}\" />",
                                $page);
                                                   
            $this->getResponse()->setBody($page);
        }
    }
}
