<?php

/**
 *
 * @see XenForo_DataWriter_AddOn
 */
class Waindigo_InstallUpgrade_Extend_XenForo_DataWriter_AddOn extends XFCP_Waindigo_InstallUpgrade_Extend_XenForo_DataWriter_AddOn
{

    /**
     *
     * @see XenForo_DataWriter_AddOn::_getFields()
     */
    protected function _getFields()
    {
        $fields = parent::_getFields();
        $fields['xf_addon']['install_upgrade_filename'] = array(
            'type' => self::TYPE_STRING,
            'default' => ''
        );
        $fields['xf_addon']['install_upgrade_updated'] = array(
            'type' => self::TYPE_UINT,
            'default' => 0
        );

        return $fields;
    }

    /**
     *
     * @see XenForo_DataWriter_AddOn::_preSave()
     */
    protected function _preSave()
    {
        $fileName = Waindigo_InstallUpgrade_ControllerHelper_InstallUpgrade::getFileName();

        if ($fileName) {
            $this->set('install_upgrade_filename', $fileName);
        }

        parent::_preSave();
    }

    /**
     *
     * @see XenForo_DataWriter_AddOn::_postSave()
     */
    protected function _postSave()
    {
        $xenOptions = XenForo_Application::get('options');

        if (XenForo_Application::isRegistered('waindigoImportXml')) {
            if ($this->get('version_id') != 1 && !$this->isChanged('version_id') &&
                 $xenOptions->waindigo_installUpgrade_allowSkipXmlImport) {
                XenForo_Application::set('waindigoImportXml', false);
            }
        }

        if (!empty($GLOBALS['XenForo_ControllerAdmin_AddOn'])) {
            /* @var $controller XenForo_ControllerAdmin_AddOn */
            $controller = $GLOBALS['XenForo_ControllerAdmin_AddOn'];

            if ($this->isInsert() && strtolower($controller->getRouteMatch()->getAction()) == 'save' && ($this->get(
                'install_callback_class') == 'Waindigo_Install' ||
                 $this->get('uninstall_callback_class') == 'Waindigo_Install')) {
                $class = $this->get('addon_id') . '_Install_Controller';
                $filename = XenForo_Autoloader::getInstance()->getRootDir() . "/" . str_replace("_", "/", $class) .
                     ".php";
                if (!file_exists($filename)) {
                    $phpFile = new Waindigo_InstallUpgrade_PhpFile_Install_Controller($class);
                    $phpFile->export(true);
                }
                if ($this->get('addon_id')) {
                    XenForo_Helper_Cookie::setCookie('edit_addon_id', $this->get('addon_id'));
                }
            }
        }

        if (XenForo_Application::$versionId > 1020000) {
            XenForo_Application::defer('Waindigo_InstallUpgrade_Deferred_UpdateCheck', array(), 'WaindigoIuUpdateCheck');
        }

        parent::_postSave();
    }
}