<?php

require_once dirname(__FILE__).'/../lib/videoGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/videoGeneratorHelper.class.php';

/**
 * video actions.
 *
 * @package    sf
 * @subpackage video
 * @author     Atma
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class videoActions extends autoVideoActions
{
    protected function processForm(sfWebRequest $request, sfForm $form)
    {
        $form->bind($request->getParameter($form->getName()), $request->getFiles($form->getName()));
        if ($form->isValid())
        {
            $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';
            try
            {
                $video = $form->save();

                $video_custom = $request->getParameter('video_custom');
                if(count($video_custom['tags']) > 0)
                {

                    foreach($video_custom['tags'] as $tag_id)
                    {
                        $newProductTags = new VideoTags();
                        $newProductTags->setVideoId($video->getId());
                        $newProductTags->setTagId($tag_id);
                        $newProductTags->save();
                    }

                }
            }
            catch (Doctrine_Validator_Exception $e)
            {
                $errorStack = $form->getObject()->getErrorStack();
                $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
                foreach ($errorStack as $field => $errors)
                {
                    $message .= "$field (" . implode(", ", $errors) . "), ";
                }
                $message = trim($message, ', ');
                $this->getUser()->setFlash('error', $message);
                return sfView::SUCCESS;
            }
            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $video)));
            if ($request->hasParameter('_save_and_add'))
            {
                $this->getUser()->setFlash('notice', $notice.' You can add another one below.');
                $this->redirect('@video_new');
            }
            elseif ($request->hasParameter('_save_and_list'))
            {
                $this->redirect('@video');
            }
            else
            {
                if(!$request->isXmlHttpRequest())
                {
                    $this->getUser()->setFlash('notice', $notice);
                    $this->redirect($request->hasParameter('return') ? $request->getParameter('return') : array('sf_route' => 'video_edit', 'sf_subject' => $video));
                }
            }
        }
        else
        {
            $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
            $this->getResponse()->addHttpMeta('Sf-Form-Error', '1', true);
        }
    }

    public function executeGdata(sfWebRequest $request)
    {
        if($request->getParameter('type') == 'youtube')
        {

            $ch = curl_init('https://www.googleapis.com/youtube/v3/videos?id=' . $request->getParameter("id") . '&key=AIzaSyACY3IFamw5LkQFiIVww38beV7O7_oHNhM&part=snippet');
            curl_setopt($ch, CURLOPT_USERAGENT, 'IE20');
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
            $text = curl_exec($ch);
            $json = json_decode($text, true);



            if(is_array($json))
            {


                $ch = curl_init($json['items'][0]['snippet']['thumbnails']['high']['url']);
                curl_setopt($ch, CURLOPT_HEADER, 0);
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
                $content = curl_exec($ch);
                curl_close($ch);
                if (file_exists('../upload/' . $request->getParameter('id') . '.jpg')) {
                    unlink('../upload/' . $request->getParameter('id') . '.jpg');
                }
                $fp = fopen('../upload/' . $request->getParameter('id') . '.jpg','x');
                fwrite($fp, $content);
                fclose($fp);

                $request->setParameter('key', 'video_yt');
                $request->setParameter('file', $request->getParameter('id') . '.jpg');
                $resize = Page::resize($request, true);
                echo json_encode(array('title' => $json['items'][0]['snippet']['title'], 'image' => $resize));
            }
        }
        elseif($request->getParameter('type') == 'vk')
        {

            $ch = curl_init('https://vk.com/video_ext.php?' . str_replace(array(':', ';'), array('=', '&'), $request->getParameter('id')));
            curl_setopt($ch, CURLOPT_USERAGENT, 'IE20');
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, '1');
            $page = curl_exec($ch);

            preg_match('/<video id="video_player" poster="(.*)" preload="none"/', $page, $matches);


            $ch = curl_init($matches[1]);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);
            $content = curl_exec($ch);
            curl_close($ch);
            if (file_exists('../upload/' . $request->getParameter('id') . '.jpg')) {
                unlink('../upload/' . $request->getParameter('id') . '.jpg');
            }
            $fp = fopen('../upload/' . $request->getParameter('id') . '.jpg','x');
            fwrite($fp, $content);
            fclose($fp);



            $request->setParameter('key', 'video_yt');
            $request->setParameter('file', $request->getParameter('id') . '.jpg');
            $resize = Page::resize($request, true);

            //preg_match('/var video_title = \'(.*)\';/', $page, $matches);

            echo json_encode(array('image' => $resize));
        }
        return sfView::NONE;
    }

    protected function buildQuery()
    {
        $query = parent::buildQuery();
        $query->leftJoin("r.Translation t");
        return $query;
    }
}
