<?php
/**
 * This class for API Service
 * @author Shahter
 */
class Backend_ApiimagesController extends RCMS_Core_BaseController {    


    public function init()
    {
	parent::init();
        parent::checkLogin();
        $this->_model = new Default_Model_ThingsModel();
    }
    
    public function loginAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $form = new RCMS_Form_LoginServiceForm();
        $form->setDecorators(array( array('ViewScript', array('viewScript' => 'forms/loginservice.phtml')) ));
        $this->view->form = $form;
        $this->view->error = false;
        $this->view->errorMessage = '';

        if ($this->getRequest()->isPost()) {
            if ($this->view->form->isValid($this->getRequest()->getParams())) {
                $service = trim($this->getRequest()->getParam('service'));
                switch ($service) {
                    case 'picasa':
                        if (isset($this->_session->picasaClient)) {
                            unset($this->_session->picasaClient);
                        }
                        $connection = $this->connectToPicasa($this->view->form->login->getValue(), $this->view->form->password->getValue());
                        if ($connection === true) {
                            $this->_redirect($this->_websiteUrl . 'sys/backend_apiimages/picasa/');
                        } else {
                            $this->view->error = true;
                            $this->view->errorMessage = '<p>Can\'t connect to server. Please check your Login or Password.</p>';
                        }
                        break;
                }
            } else {
                $this->view->error = true;
                $errors = $this->view->form->getMessages();
                $errorMessage = '';
                foreach ($errors as $key => $error) {                    
                    if (array_key_exists('isEmpty', $error)) {
                        $errorMessage .= '<p>' . ucfirst($key) . ' field can\'t be empty.</p>';
                    }
                }
                $this->view->errorMessage = $errorMessage;
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    private function connectToPicasa($login, $password)
    {
        $login = trim(strip_tags($login));
        $password = trim(strip_tags($password));
        if ($login === '' || $password === '') {
            return false;
        }
        try {
            $serviceName = Zend_Gdata_Photos::AUTH_SERVICE_NAME;
            $client = Zend_Gdata_ClientLogin::getHttpClient($login, $password, $serviceName);
            $this->_session->picasaClient = $client;
            return true;
        } catch (Zend_Gdata_App_HttpException $e) {
            if (isset($this->_session->picasaClient)) {
                unset($this->_session->picasaClient);
            }
            return false;
        } catch (Zend_Gdata_App_Exception $e) {
            if (isset($this->_session->picasaClient)) {
                unset($this->_session->picasaClient);
            }
            return false;
        }
    }

    public function picasaAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->view->error = false;
        $this->view->errorMessage = '';
        $this->view->albums = array();
        $this->view->photos = array();
        $this->view->currentAlbum = '';        
        
        if (isset($this->_session->picasaClient)) {
            $client = $this->_session->picasaClient;
        } else {
            $this->view->error = true;
            $this->view->errorMessage = '<p>You not logged.</p>';
            return;
        }
        $gp = new Zend_Gdata_Photos($client, 'Google-DevelopersGuide-1.0');

        if ($this->getRequest()->isPost()) {
            $request = $this->getRequest()->getParam('request');
            if ($request !== null) {
                switch ($request) {
                    case 'album' :
                        $nameAlbum = trim($this->getRequest()->getParam('name'));
                        if ($nameAlbum !== null) {
                            $query = new Zend_Gdata_Photos_AlbumQuery();
                            $query->setUser("default");
                            $query->setAlbumName(preg_replace("/([-,$#%^&\\\*?\/+=|{}\s+])/", '', $nameAlbum));
                            $album = $gp->getAlbumFeed($query);
                            foreach ($album as $key => $photo) {
                                $data = array();
                                if ($photo->getMediaGroup()->getContent() != null) {
                                    $mediaContentArray = $photo->getMediaGroup()->getContent();
                                    $data[0] = $mediaContentArray[0]->getUrl();
                                } else {
                                    $data[0] = '';
                                }
                                if ($photo->getMediaGroup()->getThumbnail() != null) {
                                    $mediaThumbnailArray = $photo->getMediaGroup()->getThumbnail();
                                    $data[1] = $mediaThumbnailArray[0]->getUrl();
                                } else {
                                    $data[1] = '';
                                }
                                $data[2] = (trim($photo->title->text)!==''?$photo->title->text:'');
                                $this->view->photos[] = $data;
                            }
                            $this->view->listFolders = RCMS_Tools_FilesystemTools::scanDir($this->_config->website->website->path . $this->_config->website->website->images);
                            $this->view->currentAlbum = $nameAlbum;
                            $this->_session->picasaQueue = array();
                        }
                        break;
                    default:
                        $this->view->error = true;
                        $this->view->errorMessage = 'Requset is wrong.';
                        break;
                }
            } else {
                $this->view->error = true;
                $this->view->errorMessage = 'Requset is wrong.';
            }

        } else {
            $userFeed = $gp->getUserFeed('default');
            foreach ($userFeed as $userEntry) {
                $this->view->albums[] = $userEntry;
            }
        }
		$content = $this->_translator->processScreen($this->view->render($this->getViewScript()));
		$this->_helper->viewRenderer->setNoRender(true);
		echo $content;
    }

    public function importqueuepicasaAction()
    {
        $this->_helper->getHelper('layout')->disableLayout();
        $this->_helper->viewRenderer->setNoRender(true);
        if ($this->getRequest()->isPost() && $this->getRequest()->getParam('data') !== '') {
            $data = explode('~|~', $this->getRequest()->getParam('data'));
            if (is_array($data) && count($data) > 0) {
                foreach ($data as $value) {
                    $val = explode('|||', $value);
                    $folder = str_replace(' ', '-', trim($val[1]));
                    $fileName = strtolower($val[0]);
                    $imageURL = $val[2];
                    $path = $this->_config->website->website->path . $this->_config->website->website->images . $folder . '/';
                    $flag = RCMS_Tools_FilesystemTools::mkDir($path);
                    if ($flag === true) {
                        RCMS_Tools_FilesystemTools::mkDir($path . 'original/');
                        RCMS_Tools_FilesystemTools::mkDir($path . 'small/');
                        RCMS_Tools_FilesystemTools::mkDir($path . 'medium/');
                        RCMS_Tools_FilesystemTools::mkDir($path . 'large/');
                        RCMS_Tools_FilesystemTools::mkDir($path . 'video/');
                    }
                    if (copy($imageURL , $path . 'original/' . $fileName)) {
                        $w = $this->_model->selectConfigForImage();
                        $wSmall = $w['img_small']['value'];
                        $wMedium = $w['img_medium']['value'];
                        $wLarge = $w['img_large']['value'];
                        $wMaxImage = $w['img_max_width']['value'];
                        $realSize = getimagesize($path . 'original/' . $fileName);
                        $source = $path . 'original/' . $fileName;
                        if ($realSize[0] > $wMaxImage) {
                            RCMS_Tools_Tools::resizeImage($source, $wMaxImage, 0, true);
                        }
                        if (copy($source,  $path . 'small/' . $fileName)) {
                            if (file_exists($path . 'small/' . $fileName)) {
                               RCMS_Tools_Tools::resizeImage($path . 'small/' . $fileName, $wSmall, 0, true);
					           }
                        }
                        if (copy($source,  $path . 'medium/' . $fileName)) {
                            if (file_exists($path . 'medium/' . $fileName)) {
                                RCMS_Tools_Tools::resizeImage($path . 'medium/' . $fileName, $wMedium, 0, true);
                            }
                        }
                        if (copy($source,  $path . 'large/' . $fileName)) {
                            if (file_exists($path . 'large/' . $fileName)) {
                                RCMS_Tools_Tools::resizeImage($path . 'large/' . $fileName, $wLarge, 0, true);
                            }
                        }
                    }
                }
            }
        }
    }

}
