<?php
// test/functional/backend/newsActionsTest.php

include(dirname(__FILE__).'/../../bootstrap/functional.php');

$browser = new sfBackendTestFunctional(new sfBrowser());
$browser->loadData();
$browser->setTester('doctrine', 'sfTesterDoctrine');

$languages = sfConfig::get('app_cultures_enabled');

$news = Doctrine::getTable('News')->
createQuery('n')->
leftJoin('n.Translation t')->
andWhere('t.lang = ?', 'fr')->
orderBy('n.id', 'asc')->
fetchOne();

$editUrl = sprintf('/news/%s/edit', $news->getId());

$browser->
// Uncomment this if your backend is protected by a login
//signin(array(
// 'username' => 'admin',
// 'password' => 'admin'
//)))->
get('/news')->
with('response')->begin()->
isStatusCode(200)->
end()->

info('1 - News list')->
with('response')->begin()->
checkElement('h1', '/News List/')->
checkElement('body', '/Fantomas/')->
end()->

info('2 - News edit')->
info(' 2.1 - I18n forms for all languages are embedded')->
get($editUrl)->
with('response')->begin()->
isStatusCode(200)->
checkElement('input[name$="[title]"]', count($languages))->
end()->

info(' 2.2 - I18n forms are validated')->
get($editUrl)->
click('Save', array('news' => array(
'en' => array(
'title' => 'toto',
'body' => ''
))
), array('_with_csrf' => true)
)->
with('form')->begin()->
hasErrors(1)->
isError('en[body]', 'required')->
end()->

info(' 2.3 - Empty forms are validated')->
get($editUrl)->
click('Save', array('news' => array(
'en' => array(
'title' => '',
'body' => ''
))
), array('_with_csrf' => true)
)->
with('form')->begin()->
hasErrors(0)->
end()->

info(' 2.4 - Translations are updated')->
get($editUrl)->
click('Save', array('news' => array(
'fr' => array(
'title' => 'toto tutu tata',
'body' => 'riri fifi loulou'
))
), array('_with_csrf' => true)
)->
with('form')->begin()->
hasErrors(0)->
end()->

with('doctrine')->begin()->
check('NewsTranslation', array(
'id' => $news->getId(),
'lang' => 'fr',
'title' => 'toto tutu tata'
))->
info(' 2.5 - No empty translation is created')->
check('NewsTranslation', array(
'id' => $news->getId(),
'lang' => 'en',
), false)->
end()->

info(' 2.6 - New translations can be added')->
get($editUrl)->
click('Save', array('news' => array(
'en' => array(
'title' => 'toto tutu tata',
'body' => 'riri fifi loulou'
))
), array('_with_csrf' => true)
)->

with('form')->begin()->
hasErrors(0)->
end()->

with('doctrine')->begin()->
check('NewsTranslation', array(
'id' => $news->getId(),
'lang' => 'en',
'title' => 'toto tutu tata'
))->
end()->

info(' 2.7 - Existing translations can be deleted')->
get($editUrl)->
click('Save', array('news' => array(
'fr' => array(
'title' => '',
'body' => ''
))
), array('_with_csrf' => true)
)->
with('form')->begin()->
hasErrors(0)->
end()->

with('doctrine')->begin()->
check('NewsTranslation', array(
'id' => $news->getId(),
'lang' => 'fr',
), false)->
end()
;