<?php
class Plugg_User_Main_Identity_EditImage extends Sabai_Application_Controller
{
    protected function _doExecute(Sabai_Application_Context $context)
    {
        $identity = $this->_parent->getRequestedUserIdentity($context);
        $manager = $context->plugin->getManagerPlugin();

        if ($manager instanceof Plugg_User_Manager_API) {
            $manager->userEditImage($context, $identity);
            return;
        }

        // Check permission
        if ($identity->getId() != $context->user->getId()) {
            if (!$context->user->hasPermission('user image edit any')) {
                $context->response->setError($context->plugin->_('Permission denied'));
                return;
            }
        } else {
            if (!$context->user->hasPermission('user image edit own')) {
                $context->response->setError($context->plugin->_('Permission denied'));
                return;
            }
        }

        // Validate form and submit
        $form = $this->_getForm($context, $manager, $identity);
        if ($form->validate()) {
            if ($manager->userEditImageSubmitForm($identity, $form)) {
                $context->response->setSuccess(
                    $context->plugin->_('User data updated successfully'),
                    array('path' => '/' . $identity->getId()
                ));
                $this->pluginManager->dispatch('UserIdentityEditImageSuccess', array($identity));
                return;
            }
        }

        // View
        $context->response
            ->setPageInfo($context->plugin->_('Edit image'))
            ->setVars(array(
                'form' => $form,
                'form_html' => $manager->userEditImageRenderForm($form),
            ));
    }

    private function _getForm(Sabai_Application_Context $context, $manager, $identity)
    {
        $action = $this->url->create(array('path' => '/' . $identity->getId() . '/edit_image'));
        $form = $manager->userEditImageGetForm($identity, $action);
        $form->addSubmitButtons($context->plugin->_('Submit'));
        return $form;
    }
}