<?php
/**
 * Copyright (c) 2012, Agence Française Informatique (AFI). All rights reserved.
 *
 * BOKEH is free software; you can redistribute it and/or modify
 * it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE as published by
 * the Free Software Foundation.
 *
 * There are special exceptions to the terms and conditions of the AGPL as it
 * is applied to this software (see README file).
 *
 * BOKEH is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU AFFERO GENERAL PUBLIC LICENSE for more details.
 *
 * You should have received a copy of the GNU AFFERO GENERAL PUBLIC LICENSE
 * along with BOKEH; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301  USA
 */
require_once 'AbstractControllerTestCase.php';

abstract class RechercheControllerNoticeTestCase extends AbstractControllerTestCase {
  protected $_storm_default_to_volatile = true;

  public function setUp() {
    parent::setUp();

    $this->fixture('Class_CodifAuteur',
                   ['id' => 123,
                    'libelle' => 'Bernard Génin']);

    $this->fixture('Class_CodifCentreInteret',
                   ['id' => 2,
                    'libelle' => 'marionettes']);

    $this->fixture('Class_CodifGenre',
                   ['id' => 1,
                    'libelle' => 'spectacle']);

    $this->fixture('Class_CodifTags',
                   ['id' => 3,
                    'libelle' => 'enfants']);

    $this->fixture('Class_CodifPcdm4',
                   ['id' => 4,
                    'libelle' => 'rock']);

    $this->fixture('Class_CodifDewey',
                   ['id' => 2,
                    'id_dewey' => 2,
                    'libelle' => 'enfants']);



    $this->mock_sql = $this->mock()
                     ->whenCalled('execute')->answers('')
                     ->whenCalled('fetchOne')->answers(null)
                     ->whenCalled('fetchAll')->answers([ [1, ''] ]);
    Zend_Registry::set('sql', $this->mock_sql);


    Class_Notice::beVolatile();
    Class_Exemplaire::beVolatile();
    $this->notice = Class_Notice::newInstanceWithId(345,
                                                    ['annee' => 2002,
                                                     'editeur' => 'Gallimard',
                                                     'isbn' => '1-234-56789-0',
                                                     'type_doc' => Class_TypeDoc::LIVRE,
                                                     'url_vignette' => 'NO',
                                                     'url_image' => 'NO',
                                                     'facettes' => 'A123 F2 G1 P4 Y2 B1 Lfre M1 Z3 D1',
                                                     'date_creation' => '2013-12-31',
                                                     'unimarc' => "01570nam0 2200325   450 0010007000000100033000070200017000400210027000571000041000841010008001251020007001331050018001401060006001582000106001642100075002702150044003452250023003893000125004123000020005373000137005573300265006943450018009594100051009775120027010286060033010556060060010886760012011487000045011608010039012052218529  a2-86642-370-4bbr.d8,95 EUR  aFRb00347575  aFRbDLE-20031204-51138  a20031107d2003    m  h0frey0103    ba| afre  aFR  ay   z   000y|  ar1 aCinéma d'animationbTexte impriméedessin animé, marionnettes, images de synthèsefBernard Génin  a[Paris]c\"Cahiers du cinéma\"cSCEREN-CNDPdcop. 2003gimpr. en Italie  a95 p.cill., couv. ill. en coul.d19 cm2 aLes petits cahiers  aLa couv. porte en plus : \"du crayon à l'ordinateur, pour ou contre Disney, Europe-Japon : le dessin animé aujourd'hui\"  aBibliogr. p. 93  aSCEREN = Services, cultures, éditions, ressources pour l'éducation nationale. CNDP = Centre national de documentation pédagogique  aPrésente un historique du cinéma d'animation, un survol des différentes productions nationales à travers le monde (Etats-Unis, Japon, France, Canada), les techniques du volume animé, l'image de synthèse, mais aussi l'oeuvre de Disney et le film d'auteur.  b9782866423704 032525826tLes Petits cahiers (Paris)x1633-90531 aLe cinéma d'animation| 31053394aAnimation (cinéma)| 31031625aDessins animés32195497xHistoire et critique  a791.431 |32547161aGéninbBernardf1946-....4070 0aFRbBNFc20031107gAFNOR2intermrc"])
      ->setExemplaires([Class_Exemplaire::getLoader()->newInstanceWithId(34)
                        ->setIdBib('456')
                        ->setIdOrigine('12')
                        ->setCodeBarres('12256663233656')
                        ->setSigbExemplaire(Storm_Test_ObjectWrapper::mock()
                                            ->whenCalled('isReservable')
                                            ->answers(true))]);

  }
}




class RechercheControllerPrintTest extends RechercheControllerNoticeTestCase {
  public function setUp() {

    parent::setUp();
  	$this->fixture('Class_ModeleFusion', ['id' => 1,
																				'nom' => 'article',
																				'contenu' => '<p><h1> {notice.titre_principal}</h1> <div>{notice.article.contenu} </div>
{notice.avis[<p>{avis}</p>]}
</p>',
                                          'profil_ids' => '3;4',
                                          'type' =>'Notice_View']);
    Class_AdminVar::newInstanceWithId('BABELTHEQUE_JS')->setValeur('');

  }


  /** @test */
  public function pageOnProfilOneShouldNotContainsPrintLink() {
    $this->home_profil = $this->fixture('Class_Profil',
                                        ['id'=> 1,
                                         'libelle'=> 'HomePage']);
    Class_Profil::setCurrentProfil($this->home_profil);

    $this->dispatch('/recherche/viewnotice/id/'.$this->notice->getId());
    $this->assertNotXPathContentContains('//div', 'Imprimer', $this->_response->getBody());
  }


  /** @test */
  public function pageOnProfilThreeShouldContainsPrintLink() {
    $this->home_profil = $this->fixture('Class_Profil',
                                        ['id'=> 3,
                                         'libelle'=> 'HomePage']);
        Class_Profil::setCurrentProfil($this->home_profil);
    $this->dispatch('/recherche/viewnotice/id/'.$this->notice->getId());
    $this->assertXPathContentContains('//div', 'Imprimer', $this->_response->getBody());
  }

}




class RechercheControllerReseauTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    ZendAfi_View_Helper_ShareUrl::setDefaultWebClient(Storm_Test_ObjectWrapper::mock()
                                                      ->whenCalled('open_url')
                                                      ->answers(false));
    parent::setUp();
    $this->dispatch(sprintf('recherche/reseau/id_notice/%d/type_doc/1',
                            $this->notice->getId()),
                    true);
  }


  public function tearDown() {
    parent::tearDown();
    ZendAfi_View_Helper_ShareUrl::setDefaultWebClient(null);
  }


  /** @test */
  public function getResauShouldContainsTwitterGif() {
    $this->assertXPath('//img[contains(@src, "twitter.gif")]');
  }


  /** @test */
  public function getResauShouldContainsTwitterLink() {
    $this->assertContains("$.getScript('/social-network/share/id_notice/345/type_doc/1/on/twitter/url",
                          $this->_response->getBody());
  }
}




class RechercheControllerViewNoticeBabelthequeTest extends RechercheControllerNoticeTestCase {
  /** @test */
  public function withoutBabelthequeJSShouldNotBeLoaded() {
    Class_AdminVar::newInstanceWithId('BABELTHEQUE_JS')->setValeur('');
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
    $this->assertNotXpath('//script[contains(@src, "babeltheque.js")]');
  }


  /** @test */
  public function withBabelthequeJSShouldBeLoadedWithRightId() {
    Class_AdminVar::newInstanceWithId('BABELTHEQUE_JS')->setValeur('http://www.babeltheque.com/bw_666.js');
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
    $this->assertXpath('//script[contains(@src, "babeltheque.js?bwid=666")]');
  }


  /** @test */
  public function noticeShouldNotHaveTome() {
    $this->notice->setClefChapeau("test")->save();
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);

    $this->assertNotXPathContentContains('//div[@class="entete_notice"]',"Voir tous les tomes");
  }

}




class RechercheControllerPagerTest extends RechercheControllerNoticeTestCase {
  protected $_notice;

  public function setUp() {
    parent::setUp();

    $records = array_map(function($i) { return [$i, ''];}, range(1, 45) );
    $this->mock_sql
                     ->whenCalled('fetchAll')
                     ->with("select id_notice, facettes from notices Where MATCH(titres, auteurs, editeur, collection, matieres, dewey) AGAINST('+(POMME POMMES POM)' IN BOOLEAN MODE) and MATCH(facettes) AGAINST('+T3' IN BOOLEAN MODE) order by (MATCH(alpha_titre) AGAINST(' POMME') * 1.5) + (MATCH(alpha_auteur) AGAINST(' POMME')) desc",
                            true,
                            false)
                     ->answers($records)
                     ->beStrict();

    $this->_notice = $this->fixture('Class_Notice', ['id' => 34, 'clef_oeuvre' => '']);
    $this->onLoaderOfModel('Class_Notice')
         ->whenCalled('find')
         ->with(34)
         ->answers($this->_notice)

         ->whenCalled('findAllByIds')
         ->with(range(1, 45), 10, null)
         ->answers([$this->_notice])

         ->whenCalled('findAllByIds')
         ->with(range(1, 45), 50, null)
         ->answers([$this->_notice])

         ->whenCalled('findAllByIds')
         ->with(range(1, 45), 7, null)
         ->answers([$this->_notice])

         ->beStrict();
  }


  /** @test */
  public function urlPage2ShouldBeWithListeFormatParameter() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3/liste_format/4', true);
    $this->assertXPath('//a[contains(@href, "/liste_format/4")][contains(@href,"/page/2")]',$this->_response->getBody());
  }


  /** @test */
  public function withPageSize10PageFiveShouldBePresent() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3', true);
    $this->assertXPath('//a[contains(@href,"/page/5")]',$this->_response->getBody());
  }


  /** @test */
  public function withPageSize100PageFiveShouldFallbackToMaximumPageSize50() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3/page_size/100', true);
    $this->assertXPath('//a[contains(@href,"/page_size/50")]',$this->_response->getBody());
  }


  /** @test */
  public function withPageSize10PageSixShouldNotBePresent() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3', true);
    $this->assertNotXPath('//a[contains(@href,"/page/6")]',$this->_response->getBody());
  }


  /** @test */
  public function urlWithPageSizeSevenShouldCallFindAllWithPageSize() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3/page_size/7', true);
    $this->assertXPath('//a[contains(@href, "/page_size/7")][contains(@href,"/page/2")]',$this->_response->getBody());
  }


  /** @test */
  public function withPageSizeSevenPageSevenShouldBePresent() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3/page_size/7', true);
    $this->assertXPath('//a[contains(@href,"/page/7")]',$this->_response->getBody());
  }


  /** @test */
  public function withPageSizeSevenPageHeightShouldNotBePresent() {
    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/*/facette/T3/page_size/7', true);
    $this->assertNotXPath('//a[contains(@href,"/page/8")]',$this->_response->getBody());
  }
}



class RechercheControllerViewNoticeWithPreferencesTest extends RechercheControllerNoticeTestCase {
  protected $_web_analytics_client;

  public function setUp() {
    parent::setUp();

    $time_source = new TimeSourceForTest('2013-12-27 09:00:00');
    Class_Notice::setTimeSource($time_source);

    Class_AdminVar::newInstanceWithId('FACETTE_GENRE_LIBELLE', ['valeur' => 'GENRES']);
    Class_AdminVar::newInstanceWithId('FACETTE_DEWEY_LIBELLE', ['valeur' => 'Classification']);
    Class_AdminVar::newInstanceWithId('FACETTE_PCDM4_LIBELLE', ['valeur' => 'Classification']);

    $this->notice->setClefChapeau('Gallimard serie');
    $this->notice->set_subfield('461','t', 'Gallimard serie');
    $preferences = [
                    'barre_nav' => 'Document',
                    'entete' =>"ABCDEFGIKLMNOPRSTtYZ8v9",
                    'onglets' =>  [
                                   'detail' =>          ['titre' => 'Details',      'aff' =>  '1', 'ordre' => 1, 'largeur' => 10],
                                   'avis' =>            ['titre' => 'avis',         'aff' =>  '1', 'ordre' => 2, 'largeur' => 10],
                                   'exemplaires' =>   ['titre' => 'exemplaires',  'aff' =>  '2', 'ordre' => 3, 'largeur' => 10],
                                   'resume' =>          ['titre' => 'resume',       'aff' =>  '2', 'ordre' => 4, 'largeur' => 10],
                                   'tags' =>            ['titre' => 'tags',         'aff' =>  '2', 'ordre' => 5, 'largeur' => 10],
                                   'biographie' =>      ['titre' => 'biographie',   'aff' =>  '2', 'ordre' => 6, 'largeur' => 10],
                                   'similaires' =>      ['titre' => 'similaires',   'aff' =>  '2', 'ordre' => 7, 'largeur' => 10],
                                   'bibliographie' => ['titre' => 'bibliographie','aff' =>  '3', 'ordre' => 7, 'largeur' => 10],
                                   'morceaux' =>        ['titre' => 'morceaux',     'aff' =>  '3', 'ordre' => 8, 'largeur' => 10],
                                   'bandeAnnonce' =>    ['titre' => 'bande annonce','aff' =>  '3', 'ordre' => 9, 'largeur' => 10],
                                   'photos' =>          ['titre' => 'photos',       'aff' =>  '3', 'ordre' => 14, 'largeur' =>  10],
                                   'videos' =>          ['titre' => 'videos',       'aff' =>  '3', 'ordre' => 11, 'largeur' =>  10],
                                   'resnumeriques' => ['titre' => 'ressources n', 'aff' =>  '3', 'ordre' => 12, 'largeur' =>  10],
                                   'babeltheque' =>   ['titre' => 'babeltheque',  'aff' =>  '3', 'ordre' => 13, 'largeur' =>  10],
                                   'frbr' =>            ['titre' => 'frbr',         'aff' =>  '0', 'ordre' => 10, 'largeur' =>  10],
                                   'serie' =>         ['titre' => 'serie',        'aff' =>  '0', 'ordre' => 11, 'largeur' =>  10]],
                    'boite' =>  null];

    Class_Profil::getCurrentProfil()
      ->setBarreNavOn(true)
      ->setCfgModules(['recherche' => ['viewnotice1' => $preferences]]);

    Class_TypeDoc::find(Class_TypeDoc::LIVRE)->setLabel('livres');

    $this->_web_analytics_client = Storm_Test_ObjectWrapper::mock()
      ->whenCalled('trackEvent')
      ->answers(true);
    ZendAfi_Controller_Action_Helper_TrackEvent::setDefaultWebAnalyticsClient($this->_web_analytics_client);

    $this->dispatch('recherche/viewnotice/id/345', true);
  }


  /** @test **/
  public function enteteShouldDisplayNouveaute(){
    $this->assertXPathContentContains('//dl//dt[contains(@class,"nouveaute")]/following-sibling::dd','Oui',$this->_response->getBody());
  }

  /** @test **/
  public function noticeHtmlShouldContainsDivNoticeFlagWithSpanNouveaute(){
    $this->assertXpath('//div[@class="flags_notice"]//span[@class="nouveaute"]');
  }

  /** @test */
  public function enteteShouldDisplayAnnee2002() {
    $this->assertXPathContentContains('//dl//dd', '2002');
  }


  /** @test */
  public function enteteShouldDisplayDocumentDeLaMemeSerie() {
    $this->assertXPathContentContains('//div//a[contains(@href,"Gallimard+serie")]', 'Voir tous les tomes de Gallimard serie',$this->_response->getBody());
  }



  /** @test */
  public function enteteShouldDisplayDocumentLinkOrderByDateNouveaute() {
    $this->assertXPathContentContains('//div//a[contains(@href,"Gallimard+serie/tri/date_creation+desc")]', 'Voir tous les tomes de',$this->_response->getBody());
  }


  /** @test */
  public function enteteShouldDisplayDtEditeur() {
    $this->assertXPathContentContains('//dl//dt', 'Editeur');
  }


  /** @test */
  public function enteteShouldDisplayEditeurGallimard() {
    $this->assertXPathContentContains('//dl//dd', 'Gallimard');
  }


  /** @test */
  public function enteteShouldDisplayRebondAuteurBernardGenin() {
    $this->assertXPathContentContains('//dl//dd[contains(@class, "first")]/a[contains(@href, "recherche/simple/id/345/code_rebond/A123")]', 'Bernard Génin (Auteur)', $this->_response->getBody());
  }


  /** @test */
  public function enteteShouldDisplayRebondInterestMarionettes() {
    $this->assertXPathContentContains('//dl//a[contains(@href, "recherche/simple/id/345/code_rebond/F2")]', 'marionettes', $this->_response->getBody());
  }

  /** @test */
  public function enteteShouldDisplayRebondTagEnfants() {
    $this->assertXPathContentContains('//dl//a[contains(@href, "recherche/simple/id/345/code_rebond/Z3")]', 'enfants', $this->_response->getBody());
  }

  /** @test */
  public function enteteShouldDisplayRebondPcdm4Rock() {
    $this->assertXPathContentContains('//dl//a[contains(@href, "recherche/simple/id/345/code_rebond/P4")]', 'rock', $this->_response->getBody());
  }

  /** @test */
  public function enteteShouldDisplayRebondGenreSpectacle() {
    $this->assertXPathContentContains('//dl//a[contains(@href, "recherche/simple/id/345/code_rebond/G1")]', 'spectacle');
  }


  /** @test */
  public function enteteLibelleGenreShouldBeGENRES() {
    $this->assertXPathContentContains('//dl//dt', 'GENRES');
  }


  /** @test */
  public function enteteShouldDisplayDtDdCollectionWithClassSecond() {
    $this->assertXPathContentContains('//dl//dt[contains(@class, "second")]', 'Collection',$this->_response->getBody());
  }


  /** @test */
  public function detailsBlocShouldHaveIdBloc_345_0() {
    $this->assertXPathContentContains('//div[@id="bloc_345_0"][@class="notice_bloc_titre"]', 'Details');
  }


  /** @test */
  public function javascriptShouldOpenFirstBlocDetails() {
    $this->assertXPathContentContains('//script',
                                      "infos_bloc(\"bloc_345_0\",'1-234-56789-0','detail',0,'',0, 'http://localhost".BASE_URL."/noticeajax/detail/id/345')",$this->_response->getBody());
  }


  /** @test */
  public function javascriptShouldOpenSecondBlocAvis() {
    $this->assertXPathContentContains('//script',
                                      "infos_bloc(\"bloc_345_1\",'1-234-56789-0','avis',0,'',1, 'http://localhost".BASE_URL."/noticeajax/avis/id/345')");
  }


  /** @test */
  public function noJavascriptShouldOpenThirdBlocExemplaires() {
    $this->assertNotXPathContentContains('//script', "infos_bloc(\"bloc_345_2\"",$this->_response->getBody());
  }


  /** @test */
  public function bibliographieOngletShouldHaveIdSet345_onglet_0() {
    $this->assertXPathContentContains('//div[@id="set345_onglet_0"][@class="titre_onglet"]', 'bibliographie');
  }


  /** @test */
  public function javascriptShouldOpenFirstOngletBibliographie() {
    $this->assertXPathContentContains('//script',
                                      "infos_onglet('set345_onglet_0','1-234-56789-0','bibliographie',0,'',0, 'http://localhost".BASE_URL."/noticeajax/bibliographie/id/345')");
  }


  /** @test */
  public function videosOngletShouldHaveIdSet345_onglet_3() {
    $this->assertXPathContentContains('//div[@id="set345_onglet_3"][@class="titre_onglet"]', 'videos',$this->_response->getBody());
  }

  /** @test */
  public function noJavascriptShouldOpenSecondOnglet() {
    $this->assertNotXPathContentContains('//script', "infos_onglet('set345_onglet_1')");
  }


  /** @test */
  public function linkReserverShouldBeDisplayed() {
    $this->assertXPathContentContains('//a[contains(@onclick, "openDialogExemplaires")]', 'Réserver');
  }


  /** @test */
  public function vignetteShouldBeGenerated() {
    $this->assertXPath('//div[@class="nothumbnail type_doc_1"]');
  }


  /** @test */
  public function vignetteForZoomShouldNotBeGenerated() {
    $this->assertNotXPath('//a[@id="vignette"]');
  }


  /** @test */
  public function divViewNoticeShouldHaveClassTypeDocOne() {
    $this->assertXPath('//div[@class="view_notice type_doc_1"]');
  }

  /** @test */
  public function tabTitleShouldContainTitle() {
    $this->assertXPath('//div[contains(@class, "titre_onglet") and h2]');
  }

  /** @test */
  public function pageShouldBeHTML5Valid() {
    $this->assertHTML5();
  }


  /**
   * @test
   */
  public function trackEventShouldContainsNoticeTitreAuteur() {
    $this->assertEquals(['recherche',
                         'notice',
                         '"titre: Gallimard serie<br /> Cinéma d\'animation","auteur: Bernard Génin","editeur: Gallimard","tome: ","support: livres","ressource: http://localhost'.BASE_URL.'/recherche/viewnotice/id/345"',
                         345],
                        $this->_web_analytics_client->getAttributesForLastCallOn('trackEvent'));
  }


  /**
   * @test
   * @group pagetitles
   */
  public function barreNavShouldContainsCinemaAnimation() {
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span', 'Cinéma d\'animation');
  }

  /** @test */
  public function deweyAndPcdm4WithSameLibelleShouldBePresent() {
    $this->assertXPathContentContains('//div[@class="entete_notice"]//dt[contains(@class, "classification")]', 'Classification');
    $this->assertXPathContentContains('//div[@class="entete_notice"]//dt[contains(@class, "classification")]/following::dd', 'Philosophie et disciplines connexes');
    $this->assertXPathContentContains('//div[@class="entete_notice"]//dt[contains(@class, "classification")]', 'Classification');
    $this->assertXPathContentContains('//div[@class="entete_notice"]//dt[contains(@class, "classification")]/following::dd', 'rock');
  }
}




class RechercheControllerViewNoticeTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    $this->dispatch('recherche/viewnotice/id/345', true);
  }


  /** @test */
  public function titleShouldBeDisplayed() {
    $this->assertXPathContentContains('//h1',
                                      array_first(explode('<br />', $this->notice->getTitrePrincipal())),
                                      $this->_response->getBody());
  }

  /** @test */
  public function pageShouldContainsOnlyTwoH1() {
    $this->assertXPathCount('//h1', 2, $this->_response->getBody());
  }

  /** @test */
  public function pageShouldContainsH1WithTitleAndAuthor() {
    $this->assertXPath('//h1//span[contains(text(), "Cinéma d\'animation")][following-sibling::span[text()="Bernard Génin"]]');
  }

  /** @test */
  public function tagReseauSociauxShouldBePresent() {
    $this->assertXPath('//div[@id="reseaux-sociaux"]');
  }


  /** @test */
  public function headShouldContainsRechercheJS() {
    $this->assertXPath('//head//script[contains(@src,"public/opac/js/recherche.js")]');
  }
}




class RechercheControllerViewNoticeMetasTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $this->fixture('Class_Notice',
                   ['id' => 345,
                    'titre_principal' => 'Cinéma d\'animation<br/>3D',
                    'auteur_principal' => 'Bernard Génin',
                    'annee' => 2002,
                    'editeur' => 'Gallimard',
                    'isbn' => '1-234-56789-0',
                    'type_doc' => Class_TypeDoc::LIVRE,
                    'url_vignette' => 'http://linux.org',
                    'url_image' => 'http://linux.org',
                    'facettes' => 'A123 F2 G1 P4 Y2 B1 Lfre M1 Z3 D1',
                    'date_creation' => '2013-12-31']);

    $this->dispatch('recherche/viewnotice/id/345', true);
  }


  /** @test */
  public function pageShouldContainTitleMeta() {
    $this->assertXPathContentContains('//meta[@property="og:title"]/@content', 'Cinéma d\'animation br/ 3D - Bernard Génin', $this->_response->getBody());
  }


  /** @test */
  public function pageShouldContainImageMeta() {
    $this->assertXPathContentContains('//meta[@property="og:image"]/@content', 'http://linux.org');
  }


  /** @test */
  public function pageShouldContainDescriptionMeta() {
    $this->assertXPath('//meta[@property="og:description"]/@content');
  }

}




class RechercheControllerVignetteTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    $this->dispatch('recherche/vignette/id_notice/345', true);
  }

  /** @test */
  public function responseShouldRedirectToVignetteUrl() {
    $this->assertContains('/temp/vignettes_titre/notice_345.png',
                          $this->getResponseLocation());
  }
}




class RechercheControllerVignetteEmptyTest extends RechercheControllerNoticeTestCase {
  protected $_storm_default_to_volatile = true;

  public function setUp() {
    parent::setUp();

    $article = $this->fixture('Class_Article',
                   ['id' => 123,
                    'titre' => 'An article with img',
                    'contenu' => 'This article should contains an image like this <img src="/images/articles/img.png" />']);
    $article->index();
    $this->dispatch('recherche/vignette/id_notice/1', true);
  }


  /** @test */
  public function responseShouldRedirectToVignetteUrl() {
    $this->assertContains('/temp/vignettes_titre/notice_1.png',
                          $this->getResponseLocation());
  }
}




class RechercheControllerViewNoticeClefAlphaTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $this->mock_sql
                     ->whenCalled('fetchAll')
                     ->with("select id_notice, facettes from notices Where MATCH(titres, auteurs, editeur, collection, matieres, dewey) AGAINST('+(MILLENIUM MILLENIUMS MILENIUM)' IN BOOLEAN MODE) order by (MATCH(alpha_titre) AGAINST(' MILLENIUM') * 1.5) + (MATCH(alpha_auteur) AGAINST(' MILLENIUM')) desc", true, null)
                     ->answers([
                                [10, ''],
                                [99, ''],
                                [88, ''],
                                [$this->notice->getId(), ''],
                                [2, ''],
                                [34,''],
                                [4, '']
                                ]);

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('findAllBy')
      ->with(['clef_alpha' => 'TESTINGALPHAKEY---101'])
      ->answers([$this->notice]);

    $this->dispatch('recherche/viewnotice/clef/TESTINGALPHAKEY---101/expressionRecherche/Millenium', true);
  }

  /** @test */
  public function retourListeShouldLinkToRechercheSimpleWithHashTagIdNotice() {
    $this->assertXPathContentContains('//div/a[@class="retour"][contains(@href, "/recherche/simple/expressionRecherche/Millenium#345")]',
                                      'Retour à la liste');
  }

  /** @test */
  public function resultatSuivantShouldLinkToNavigationSuivant() {
    $this->assertXPathContentContains('//div//a[contains(@href, "recherche/viewnotice/clef/TESTINGALPHAKEY---101/expressionRecherche/Millenium/navigation/suivant")]',
                                      'Document suivant', $this->_response->getBody());
  }

  /** @test */
  public function resultatPrecedentShouldLinkToNavigationPrecedent() {
    $this->assertXPathContentContains('//div//a[contains(@href, "recherche/viewnotice/clef/TESTINGALPHAKEY---101/expressionRecherche/Millenium/navigation/precedent")]',
                                      'Document précédent', $this->_response->getBody());
  }
}




class RechercheControllerViewNoticeClefAlphaWithDoublonsTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('findAllBy')
      ->with(['clef_alpha' => 'TWILIGHT--SLADED-3-M6VIDEO-2010-4'])
      ->answers([Class_Notice::newInstanceWithId($this->notice->getId())
                 ->setTitrePrincipal('Twilight 1')
                 ->setClefAlpha('TWILIGHT--SLADED-3-M6VIDEO-2010-4')
                 ->setFacettes('')
                 ->setUrlVignette('NO')
                 ->setUrlImage('NO'),

                 Class_Notice::newInstanceWithId(1)
                 ->setTitrePrincipal('Twilight 2')
                 ->setClefAlpha('TWILIGHT--SLADED-3-M6VIDEO-2010-4')
                 ->setFacettes('')
                 ->setUrlVignette('')
                 ->setUrlImage('')
                 ->setDateCreation('')
                 ]);
  }


  /** @test */
  public function withOnlyClefResponseShouldRedirectToRechercheTWILIGHT_SLADED() {
    $this->dispatch('recherche/viewnotice/clef/'.urlencode('TWILIGHT--SLADED-3-M6VIDEO-2010-4'), true);
    $this->assertRedirectTo('/opac/recherche?q=TWILIGHT+SLADED');
  }


  /** @test */
  public function withClefAndIdResponseShouldRenderTwilight2() {
    $this->dispatch('recherche/viewnotice/clef/'.urlencode('TWILIGHT--SLADED-3-M6VIDEO-2010-4').'/id/1', true);
    $this->assertXPathContentContains('//div[contains(@class, "view_notice")]//h1', 'Twilight 2');
  }
}




class RechercheControllerUploadVignetteTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    Class_CodifTypeDoc::beVolatile();

    $this->notice->setTypeDoc(5);
  }


  /** @test */
  public function linkToUploadVignetteShouldNotBePresentForAbonneSIGB() {
    Class_Users::getIdentity()->beAbonneSIGB();
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
    $this->assertNotXPathContentContains('//a', 'Modifier la vignette');
  }


  /** @test */
  public function linkToUploadVignetteShouldBePresentForModoBib() {
    Class_Users::getIdentity()->changeRoleTo(ZendAfi_Acl_AdminControllerRoles::MODO_BIB);
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
    $this->assertXPathContentContains('//a', 'Modifier la vignette');
  }


  /** @test */
  public function linkToUploadVignetteShouldNotBePresentForTypeDocMoreThanFive() {
    Class_Users::getIdentity()->beAdminPortail();
    $this->notice->setTypeDoc(6);
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
    $this->assertNotXPathContentContains('//a', 'Modifier la vignette');
  }


  /** @test */
  public function linkToUploadVignetteShouldBePresentForTypeDocThanFiveWhenInKnownFamille() {
    Class_Users::getIdentity()->beAdminPortail();
    $this->notice->setTypeDoc(Class_TypeDoc::EPUB);
    $this->fixture('Class_CodifTypeDoc', ['id' => Class_TypeDoc::EPUB,
                                          'famille_id' => Class_CodifTypeDoc::LIVRE]);

    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
    $this->assertXPathContentContains('//a', 'Modifier la vignette');
  }
}




class RechercheControllerViewNoticeAsAdminTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    $this->notice->setTypeDoc(5);
    Class_Users::getIdentity()->beAdminPortail();

    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
  }


  /** @test */
  public function linkToUploadVignetteShouldBePresent() {
    $this->assertXPathContentContains('//a', 'Modifier la vignette',$this->_response->getBody());
  }


  /** @test */
  public function linkToConfigModulesRechercheShouldHaveActionViewNotice() {
    $this->assertXPath('//img[contains(@onclick, "admin/modules/recherche?config=site&type_module=recherche&id_profil=2&action1=viewnotice&action2=5")]');
  }


  /** @test */
  public function linkToDeleteBlockShouldNotBePresent() {
    $this->assertNotXPath('//a[contains(@href, "/admin/accueil/delete-block")]');
  }


  /** @test */
  public function linkToAddBlockShouldNotBePresent() {
    $this->assertNotXPath('//img[contains(@onclick, "/admin/accueil/add-block")]');
  }


  /** @test */
  public function pageShouldBeHTML5Valid() {
    $this->assertHTML5();
  }
}



class RechercheControllerViewNoticeAndResnumeriqueTabAsAdminTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    Class_Users::getIdentity()->beAdminPortail();

    $preferences = ['barre_nav' => 'Document',
                    'entete' =>"ABCDEFGIKLMNOPRSTtYZ8v9",
                    'onglets' =>  ['detail' =>          ['titre' => 'Details',
                                                         'aff' => '1',
                                                         'ordre' => 1,
                                                         'largeur' => 10],
                                   'avis' =>            ['titre' => 'avis',
                                                         'aff' => '1',
                                                         'ordre' => 2,
                                                         'largeur' => 10],
                                   'exemplaires' =>     ['titre' => 'exemplaires',
                                                         'aff' => '2',
                                                         'ordre' => 3,
                                                         'largeur' => 10],
                                   'resume' =>          ['titre' => 'resume',
                                                         'aff' => '2',
                                                         'ordre' => 4,
                                                         'largeur' => 10],
                                   'tags' =>            ['titre' => 'tags',
                                                         'aff' => '2',
                                                         'ordre' => 5,
                                                         'largeur' => 10],
                                   'biographie' =>      ['titre' => 'biographie',
                                                         'aff' => '2',
                                                         'ordre' => 6,
                                                         'largeur' => 10],
                                   'similaires' =>      ['titre' => 'similaires',
                                                         'aff' => '2',
                                                         'ordre' => 7,
                                                         'largeur' => 10],
                                   'bibliographie' =>   ['titre' => 'bibliographie',
                                                         'aff' => '3',
                                                         'ordre' => 7,
                                                         'largeur' => 10],
                                   'morceaux' =>        ['titre' => 'morceaux',
                                                         'aff' => '3',
                                                         'ordre' => 8,
                                                         'largeur' => 10],
                                   'bandeAnnonce' =>    ['titre' => 'bande annonce',
                                                         'aff' => '3',
                                                         'ordre' => 9,
                                                         'largeur' => 10],
                                   'photos' =>          ['titre' => 'photos',
                                                         'aff' => '3',
                                                         'ordre' => 14,
                                                         'largeur' => 10],
                                   'videos' =>          ['titre' => 'videos',
                                                         'aff' => '3',
                                                         'ordre' => 11,
                                                         'largeur' => 10],
                                   'resnumeriques' =>   ['titre' => 'ressources n',
                                                         'aff' => '2',
                                                         'ordre' => 12,
                                                         'largeur' => 10],
                                   'babeltheque' =>     ['titre' => 'babeltheque',
                                                         'aff' => '3',
                                                         'ordre' => 13,
                                                         'largeur' => 10],
                                   'frbr' =>            ['titre' => 'frbr',
                                                         'aff' => '0',
                                                         'ordre' => 10,
                                                         'largeur' => 10],
                                   'serie' =>           ['titre' => 'serie',
                                                         'aff' => '0',
                                                         'ordre' => 11,
                                                         'largeur' => 10]],
                    'boite' =>  null];

    Class_Profil::beVolatile();
    $this->fixture('Class_Profil', ['id' => 1,
                                    'libelle' => 'Afibre'])
      ->setBarreNavOn(true)
      ->setCfgModules(['recherche' => ['viewnotice1' => $preferences]])
      ->beCurrentProfil();
    $this->dispatch(sprintf('recherche/viewnotice/id/%d', $this->notice->getId()), true);
  }


  /** @test */
  public function resnumeriquesBlocShouldBePresent() {
    $this->assertXPathContentContains('//div[@class="resnumeriques block_info_notice"]//h2', 'ressources n');
  }
}




class RechercheControllerReadNoticeTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    $this->dispatch(sprintf('recherche/readnotice/id/%d', $this->notice->getId()), true);
  }


  /** @test */
  public function titreShouldBeDisplayed() {
    $this->assertXPathContentContains('//p', 'Titre: Cinéma d\'animation');
  }


  /** @test */
  public function auteurShouldBeDisplayed() {
    $this->assertXPathContentContains('//p', 'Auteur: Bernard Génin');
  }

  /** @test */
  public function anneeShouldBe2002() {
    $this->assertXPathContentContains('//p', 'Année: 2002');
  }
}



abstract class RechercheAvanceeControllerSimpleActionTestCase extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    Class_AdminVar::newInstanceWithId('FACETTE_TYPE_DOC_LIBELLE', ['valeur' => 'Type de document']);
  }
}




class RechercheAvanceeControllerSimpleActionWithDefaultConfigTest extends RechercheAvanceeControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()->setCfgModules([]);

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('findAllByRequeteRecherche')
      ->answers([$this->fixture('Class_Notice', ['id' => 8])]);

    $mock_moteur_recherche = Storm_Test_ObjectWrapper::mock();
    $mock_search_result = Storm_Test_ObjectWrapper::mock();

    $mock_search_result
      ->whenCalled('getCriteresRecherche')
      ->answers(new Class_CriteresRecherche())

      ->whenCalled('getRecordsCount')
      ->answers(5)

      ->whenCalled('getRubrics')
      ->answers([])

      ->whenCalled('getBreadcrumb')
      ->answers([])

      ->whenCalled('fetchRecords')
      ->answers([])

      ->whenCalled('isError')
      ->answers(false)

      ->whenCalled('fetchFacetsAndTags')
      ->answers(['facettes' => [],
                 'suggests' => [
                                [
                                 'id' => 'M1355',
                                 'label' => 'CD (Sujet)'
                                ]
                 ],
                 'tags' => [
                            1=>[
                                "id" => "M1355",
                                "libelle"  => "CD",
                                "nombre" => 10],
                            2=>[
                                "id" => "M12",
                                "libelle"  => "DVD",
                                "nombre" => 5],

                 ]]);

    $mock_moteur_recherche
      ->whenCalled('lancerRecherche')
      ->answers($mock_search_result);

    Class_MoteurRecherche::setInstance($mock_moteur_recherche);

    $this->dispatch('/recherche/simple?rech_titres=maupassant',true);
  }


  /** @test */
  public function tagsCloudLevel5ShouldBePresent() {
    $this->assertXPath('//a[contains(@class,"nuage_niveau5")]',
                       $this->_response->getBody());
  }


  /** @test */
  public function tagsCloudLevel10ShouldBePresent() {
    $this->assertXPath('//a[contains(@class,"nuage_niveau10")]',
                       $this->_response->getBody());
  }


  /** @test */
  public function orderSelectShouldHaveLabel() {
    $this->assertXPath('//label[@for="tri"]',
                       $this->_response->getBody());
  }


  /** @test */
  public function suggestsBoxShouldContainsLinkToReboundCD() {
    $this->assertXPathContentContains('//div[@class="suggests facette"]/ul/li/a[contains(@href, "code_rebond/M1355")]',
                                      'CD (Sujet)',
                                      $this->_response->getBody());
  }
}




abstract class RechercheControllerSimpleActionTestCase extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    Class_AdminVar::newInstanceWithId('FACETTE_TYPE_DOC_LIBELLE', ['valeur' => 'Type de document']);
  }
}



class RechercheControllerSimpleActionWithDefaultConfigTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()->setCfgModules([]);

    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/alpha_auteur',true);

  }



  /** @test */
  public function pageShouldContainsLinkToAtomFormat() {
    $this->assertXPath('//a[contains(@href, "/recherche/simple/expressionRecherche/pomme/tri/alpha_auteur/format/atom")]/img[contains(@src, "rss")]',
                       $this->_response->getBody());
  }


  /** @test */
  public function pommeShouldBePresentInRedirectedPageAsResultatInSession() {
    $this->assertXPathContentContains('//div', 'pomme');
  }


  /** @test */
  public function pageShouldContainsLinkToSuggestionAchats() {
    $this->assertXPathContentContains('//a[contains(@href, "/abonne/suggestion-achat")]',
                                      'Suggérer un achat');
  }


  /** @test */
  public function selectedTriShouldBeAlphaAuteur() {
    $this->assertXPath('//select[@name="tri"]//option[@value="alpha_auteur"][@selected="selected"]');

  }


  /** @test */
  public function facetteWidgetTitleShouldBeAsExpected() {
    $this->assertXPathContentContains('//div[@class="facette_outer"]/h2', 'Affiner le résultat...');
  }


  /** @test */
  public function tagsCloudWidgetTitleShouldBeAsExpected() {
    $this->assertXPathContentContains('//div[contains(@class,"nuage_outer")]/h2', 'Elargir la recherche...');
  }
}




class RechercheControllerIndexActionTestWithParamQ extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    $this->dispatch('/recherche/index?q=pomme',true);
  }


  /** @test */
  public function pommeShouldBePresentInResult() {
    $this->assertXPathContentContains('//div', 'pomme');
  }
}




class RechercheControllerSimpleActionWithConfigWithoutSuggestionAchatAsAdminTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()->setCfgModules(['recherche' => ['resultatsimple' => ['suggestion_achat' => 0,
                                                                                          'liste_format' => 3]]]);
    $_SESSION['recherche'] = ['selection' => ['expressionRecherche' => 'potter',
                                              'mode' => 'simple'],
                              'resultat' => ['req_liste' => "select id_notice,MATCH(alpha_titre)  AGAINST(' (POMME POMMES POM)' ) as rel1, MATCH(alpha_auteur) AGAINST(' (POMME POMMES POM)' ) as rel2 from notices Where MATCH(titres,auteurs,editeur,collection,matieres,dewey) AGAINST('+(POMME POMMES POM)' IN BOOLEAN MODE) order by (rel1 * 1.5)+(rel2) desc",
                                             'req_facettes' => "select id_notice,type_doc,facettes from notices Where MATCH(titres,auteurs,editeur,collection,matieres,dewey) AGAINST('+(POMME POMMES POM)' IN BOOLEAN MODE)",
                                             'nombre' => 5,
                                             'facettes' => [],
                                             'tags' => []]];
    Class_Users::getIdentity()->beAdminPortail();
    $this->dispatch('/recherche/simple', true);
  }


  /** @test */
  public function pageShouldNotContainsLinkToSuggestionAchats() {
    $this->assertNotXPath('//a[contains(@href, "/abonne/suggestion-achat")]');
  }


  /** @test */
  public function linkToConfigModulesRechercheShouldHaveActionResultatAction2Simple() {
    $this->assertXPath('//img[contains(@onclick, "admin/modules/recherche?config=site&type_module=recherche&id_profil=2&action1=resultat&action2=simple")]');
  }
}




class RechercheControllerSimpleActionWithWrongParametersTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/zork', true);
  }


  /** @test */
  public function pageShouldDisplayResults() {
    $this->assertXPathContentContains('//div', 'pomme');
  }
}



class RechercheControllerSimpleActionWithNoResultsTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    $this->dispatch('/recherche/simple/expressionRecherche/%nuaisteauei', true);
  }


  /** @test */
  public function pageShouldDisplayAucunResultatTrouve() {
    $this->assertXPathContentContains('//div//div//h2',
                                      'Aucun résultat trouvé');
  }
}




abstract class RechercheControllerSimpleActionListeFormatTestCase extends AbstractControllerTestCase {
  protected $_liste_format;

  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' => ['resultatsimple' => [
                                                            'liste_format' => $this->_liste_format ,
                                                            'liste_codes' => "TANECR"]]])
      ->setSelTypeDoc('1;2;3;4;5');



    Class_IntBib::newInstanceWithId(1, ['nom_court' => 'Annecy']);
    $bib_mock = Storm_Test_ObjectWrapper::mock()
      ->whenCalled('getSigbExemplaire')->answers(false)
      ->whenCalled('getId')->answers(1)
      ->whenCalled('getLibelle')->answers('Tombouctou');

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Bib')->whenCalled('find')->answers($bib_mock);
    Class_TypeDoc::newInstanceWithId(1, ['label' => 'Livres']);
    Class_TypeDoc::newInstanceWithId(2, ['label' => 'Périodique']);


  }
}


class RechercheControllerSimpleActionWithListeFormatMurTest extends RechercheControllerSimpleActionListeFormatTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR;
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
  }


  /** @test **/
  public function resumeNoticeLinkShouldBeReset() {
    $this->assertXPathContentContains('//head/script', "/noticeajax/resumenotice';", $this->_response->getBody());
  }


  /** @test */
  public function pageShouldContainsDivNotice() {
    $this->assertXPath('//div[@class="liste_mur"]//div[@class="notice"]');
  }


  /** @test */
  public function urlForSousFacettesShouldContainsFacettesT1AndB1() {
    $this->assertXPath('//div[@class="facette"]//a[contains(@href,"/facettes/T1-B1")]',
                       $this->_response->getBody());
  }


  /** @test */
  public function urlForSousFacettesShouldNotContainsPage() {
    $this->assertNotXPath('//div[@class="facette"]//a[contains(@href,"/page/2")]');
  }


  /** @test */
  public function criteresRechercheShouldContainsBibAnnecy() {
    $this->assertXPathContentContains('//div[@class="criteres_recherche"]//div[2]', 'Bibliothèque: Annecy');
  }


  /** @test */
  public function facetteBibAnnecyShouldHaveLinkToRemove() {
    $this->assertXPath('//div[@class="criteres_recherche"]//div[2]//a[@href="/recherche/simple/expressionRecherche/potter/facettes/T1"]');
  }


  /** @test */
  public function criteresRechercheShouldContainsTypeDocLivre() {
    $this->assertXPathContentContains('//div[@class="criteres_recherche"]//div', 'Type de document: Livre');
  }

  /** @test */
  public function iconeSupportShouldHaveTitleLivres() {
    $this->assertXPath('//img[@class="icone_support"][@title="Livres"]');
  }

  /** @test */
  public function pageResultatMurShouldBeHTML5Valid() {
    $this->assertHTML5();
  }
}




class RechercheControllerListeCodeWithNouveauteTest extends RechercheControllerNoticeTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR;

  public function setUp() {
    parent::setUp();
    $time_source = new TimeSourceForTest('2013-12-14 09:00:00');
    Class_Notice::setTimeSource($time_source);
    Class_Notice::beVolatile();
    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('findAllBy')
      ->answers([Class_Notice::newInstanceWithId(8,
                                                 ['clef_alpha'=>'Nouvelle année',
                                                  'clef_oeuvre' =>'NA',
                                                  'url_vignette'=>'no',
                                                  'url_image'=>'no',
                                                  'date_creation'=> '2013-12-30']),
                 Class_Notice::newInstanceWithId(9,
                                                 ['clef_alpha'=>'New Year',
                                                  'clef_oeuvre' =>'NY',
                                                  'url_vignette'=>'no',
                                                  'url_image'=>'no',
                                                  'date_creation'=> '2013-12-30'])]);

    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' => ['resultatsimple' => [
                                                            'liste_format' => $this->_liste_format ,
                                                            'liste_codes' => "TAN9"]]]);
    $this->dispatch('/recherche/simple/expressionRecherche/hello/tri/%2A/facette/T1', true);
  }

  /** @test **/
  public function pageShouldContainsNoticeWithDivNouveauté() {
    $this->assertXPathContentContains('//div[@class="liste_mur"]//div[@class="notice"]//span[@class="notice_nouveaute"]','Nouveauté');
  }
}



class RechercheControllerFacetteSelectedTest extends RechercheControllerNoticeTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR;

  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' => ['resultatsimple' => [
                                                            'liste_format' => $this->_liste_format ,
                                                            'liste_codes' => "TANECR"]]])
      ->setSelTypeDoc('1;2;3;4;5');

    $this->dispatch('/recherche/simple/expressionRecherche/hello/tri/%2A/facette/T1', true);
  }

  /** @test */
  public function pageShouldContainsDivNotice() {
    $this->assertXPath('//div[@class="liste_mur"]//div[@class="notice"]', $this->_response->getBody());
  }


/** @test */
  public function pageShouldContainsFacettes() {
    $this->assertXPath('//div[@class="facette"]');
  }


  /** @test */
  public function facetteLivresShouldBeChecked() {
    $this->assertXPath('//div[@class="facette"]//li[contains(@class," selected")]',$this->_response->getBody());
  }


  /** @test */
  public function liFacetteLivresShouldHaveSiblingsAWidthHrefRemoveFacetteLivre() {
    $this->assertXPath('//div[@class="facette"]//li[contains(@class," selected")]/a[@href="/recherche/simple/expressionRecherche/hello/tri/%2A"]',$this->_response->getBody());
  }
}



class RechercheControllerSimpleActionLibelleFacetteTest extends RechercheControllerNoticeTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR;
  public function setup() {
    parent::setup();
    Class_AdminVar::newInstanceWithId('FACETTE_AUTEUR_LIBELLE', ['valeur' => 'Les super auteurs']);
    Class_AdminVar::newInstanceWithId('FACETTE_DEWEY_LIBELLE', ['valeur' => 'DEWEY ?!@']);

    $this->dispatch('/recherche/simple/?'.
                    'operateur_titres=and'.
                    '&rech_titres='.
                    '&operateur_auteurs=and'.
                    '&rech_auteurs=musso'.
                    '&operateur_matieres=and'.
                    '&rech_matieres='.
                    '&operateur_dewey=and'.
                    '&rech_dewey=pomme'.
                    '&operateur_editeur=and'.
                    '&rech_editeur='.
                    '&operateur_collection=and'.
                    '&rech_collection='.
                    '&type_recherche=fulltext'.
                    '&tri=*'.
                    '&annee_debut='.
                    '&annee_fin='.
                    '&nouveaute='.
                    '&annexe='.
                    '&section=', true);
  }


  /** @test */
  public function criteresRechercheShouldContainsLesAuteurs() {
    $this->assertXPathContentContains('//div[@class="criteres_recherche"]//div', 'Les super auteurs',$this->_response->getBody());
  }


  /** @test */
  public function criteresRechercheShouldContainsDEWEY() {
    $this->assertXPathContentContains('//div[@class="criteres_recherche"]//div', 'DEWEY ?!@',$this->_response->getBody());
  }
}



class RechercheControllerSimpleActionWithListeFormatVignettesTest extends RechercheControllerSimpleActionListeFormatTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_VIGNETTES;
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
  }



  /** @test */
  public function withOutLoggedUserPopupLoginShouldBeInitialized() {
    $this->assertXPathContentContains('//script', 'initializePopups');
  }


  /** @test */
  public function linkAddToCartShouldBePresent() {
    $this->assertXPath('//div[@class="vignette_lien_panier"]//a[contains(@href, "/panier/ajout-ajax/id_notice/")][@data-popup="true"]');
  }


  /** @test */
  public function pageShouldContainsDivListeVignette() {
    $this->assertXPath('//div[@class="liste_vignettes"]');
  }

  /** @test */
  public function pageShouldContainsTdAnnee() {
    $this->assertXPathContentContains('//div[@class="liste_vignettes"]//dt', 'Année');
  }

  /** @test */
  public function pageShouldContainsTdEditeur() {
    $this->assertXPathContentContains('//div[@class="liste_vignettes"]//dt', 'Editeur');
  }


  /** @test */
  public function pageShouldContainsTdCollection() {
    $this->assertXPathContentContains('//div[@class="liste_vignettes"]//dt', 'Collection');
  }


  /** @test */
  public function pageShouldContainsTdResume() {
    $this->assertXPathContentContains('//div[@class="liste_vignettes"]//dt', 'Résumé');
  }


  /** @test */
  public function pageResultatVignetteShouldBeHtml5Valid() {
    $this->assertHTML5();
  }

  /** @test */
  public function noticeUrlShouldContainsExpressionRecherchePotter() {
    $this->assertXPath('//div[@class="vignette_titre"]//a[contains(@href,"expressionRecherche/potter")]');
  }
}




class RechercheControllerSimpleActionWithListeFormatChronoTest extends RechercheControllerSimpleActionListeFormatTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_CHRONO;
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
  }
  /** @test */
  public function pageShouldContainsDivListeChrono() {
    $this->assertXPath('//div[@class="liste_chrono"][@id="liste_chrono_1"]');
  }


  /** @test */
  public function timelineJSShouldBeLoaded() {
    $this->assertXPath('//script[contains(@src, "public/opac/TimelineJS-2.25/compiled/js/storyjs-embed.js")]');
  }


  /** @test */
  public function createStoryJSFunctionShouldBeIncluded() {
    $this->assertXPathContentContains('//script', 'createStoryJS');
    $this->assertXPathContentContains('//script', '"embed_id":"liste_chrono_3"', $this->_response->getBody());
  }


  /** @test */
  public function withListeFormat3InUrlShouldDisplayWithModeVignettes() {
    $this->bootstrap();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2/liste_format/3', true);
    $this->assertXPath('//div[@class="liste_vignettes"]');
  }
}




class RechercheControllerSimpleActionWithListeFormatAccordeonTest extends RechercheControllerSimpleActionListeFormatTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_ACCORDEON;
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
  }


  /** @test */
  public function ajaxToGetNotice() {
    $this->assertXPath('//img[contains(@onclick, "getNoticeAjax")]');
  }
}




class RechercheControllerSimpleActionWithListeFormatTableauTest extends RechercheControllerSimpleActionListeFormatTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_TABLEAU;
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
  }


  /** @test */
  public function pageShouldContainsTdWithListeTitres() {
    $this->assertXPath('//td[@class="listeTitre"]');
  }
}




class RechercheControllerSimpleByISBNActionTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/2-203-00119-4', true);
  }


  /** @test */
  public function pageResultatRechecheShouldBeDisplayed() {
    $this->assertXPathContentContains('//span', '2-203-00119-4',$this->_response->getBody());
  }
}




class RechercheControllerRebondTest extends AbstractControllerTestCase {
  public function setUp() {
    parent::setUp();
    $facettes = Class_Notice::findFirstBy(['where' => 'facettes>""'])->getFacettes();
    $code_rebond = explode(' ', trim($facettes))[0];
    $this->dispatch('/recherche/simple/expressionRecherche/Potter/code_rebond/'.$code_rebond.'/tri/alpha_titre', true);
  }


  /** @test */
  public function comboTriShouldHaveAnneePublicationSelected() {
    $this->assertXPathContentContains('//select[@id="tri"]//option[@value="alpha_titre"][@selected="selected"]',
                                      'Titre',$this->_response->getBody());
  }


  /** @test */
  public function lienRetourRechercheInitialeShouldBeRechercheSimple() {
    $this->assertXPathContentContains('//a[@href="/recherche/saisie/expressionRecherche/Potter/tri/alpha_titre"]',
                                      'Retour',
                                      $this->_response->getBody());
  }


  /** @test */
  public function lienNouvelleRechercheShouldBeRechercheSimple() {
    $this->assertXPathContentContains('//a[@href="/recherche/saisie"]',
                                      'Nouvelle recherche',
                                      $this->_response->getBody());
  }
}




class RechercheControllerRebondWithFacettesTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/france/facette/T1/tri/alpha_titre/page/2', true);
  }


  /** @test */
  public function rebondUrlShouldNotContainsFacettesAndPage() {
    $this->assertXPath("//div[@class=\"nuage\"]//a[contains(@href,'/recherche/simple/expressionRecherche/france/tri/alpha_titre/code_rebond/')]",
                       $this->_response->getBody());
  }
}




class RechercheControllerGuideeTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();



    $this->mock_sql = Storm_Test_ObjectWrapper::mock();

    Zend_Registry::set('sql', $this->mock_sql);
    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with('select * from codif_dewey where LENGTH(id_dewey)=1 order by id_dewey')
      ->answers([ ['id_dewey'=>66,
                   'libelle' => 'Generalites',
                   'nb_notices'=>1],

                 ['id_dewey'=>77,
                  'libelle' => 'Arts',
                  'nb_notices' => 0]]
      )->beStrict();


    Class_CodifDewey::newInstanceWithId(66, ['libelle' => 'Generalites']);
    Class_CodifDewey::newInstanceWithId(77, ['libelle' => 'Arts']);

    Class_AdminVar::newInstanceWithId('FACETTE_DEWEY_LIBELLE', ['valeur' => 'Bouquins']);

    $this->dispatch('/recherche/simple/rubrique/X1/fil/;X1', true);
  }


  /** @test */
  public function indiceShouldBeDisplayed() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/X1')]",
                                      'Bouquins',
                                      $this->_response->getBody());
  }


  /** @test */
  public function generalitesShouldBeDisplayed() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/D66')]", 'Generalites');
  }


  /** @test */
  public function artsShouldBeDisplayed() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/D77')]", 'Arts');
  }
}




class RechercheControllerGuideeHomePageTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $this->mock_sql = Storm_Test_ObjectWrapper::mock();

    Zend_Registry::set('sql', $this->mock_sql);
    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with('select * from codif_dewey where LENGTH(id_dewey)=1 order by id_dewey')
      ->answers([[      'id_dewey'=>66,
                  'libelle' => 'Generalites',
                  'nb_notices'=>1],

                 [      'id_dewey'=>77,
                  'libelle' => 'Arts',
                  'nb_notices' => 0]]
      )->beStrict();

    $this->mock_sql
      ->whenCalled('fetchOne')
      ->with('select libelle from codif_dewey where id_dewey=\'66\'')
      ->answers( 'Generalites')->beStrict();

    $this->mock_sql
      ->whenCalled('fetchOne')
      ->with('select libelle from codif_dewey where id_dewey=\'77\'')
      ->answers('Arts')->beStrict();


    Class_AdminVar::newInstanceWithId('FACETTE_DEWEY_LIBELLE', ['valeur' => 'Bouquins']);
    Class_AdminVar::newInstanceWithId('FACETTE_PCDM4_LIBELLE', ['valeur' => 'Zic']);

    $this->dispatch('/recherche/guidee', true);
  }

  /** @test */
  public function x1ShouldBeDisplayedWithLibelleBouquins() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/X1')]",
                                      'Bouquins');
  }


  /** @test */
  public function x2ShouldBeDisplayedWithLibelleZic() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/X2')]",
                                      'Zic');
  }
}




abstract class RechercheControllerSearchResultGuideeFixtures extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $this->mock_sql = Storm_Test_ObjectWrapper::mock();
    $this->mock_moteur_recherche = Storm_Test_ObjectWrapper::mock();
    $this->mock_codif = Storm_Test_ObjectWrapper::mock();

    $this->mock_moteur_recherche
      ->whenCalled('getFacettes')
      ->answers([ "facettes" => [ "D" =>
                                 [ "D3" => 2 ]
                                   ] ,
                 'suggests' => [],
                 "tags" => [
                            1=>[
                                "id" => "M1355",
                                "libelle"  => "CD",
                                "nombre" => 2]],
                 "url_facette" => "/recherche/simple/facettes/"
                 ]

      );

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('findAllByRequeteRecherche')
      ->answers([Class_Notice::newInstanceWithId(8),
                 Class_Notice::newInstanceWithId(9)]);

    $this->mock_codif
      ->whenCalled('getNomFacette')
      ->answers('nom de la facette');

    $this->mock_codif
      ->whenCalled('getLibelleFacette')
      ->answers('facette');
    $this->mock_codif
      ->whenCalled('getNomChamp')
      ->answers('champ');


    $this->mock_moteur_recherche
      ->whenCalled('lancerRecherche')
      ->willDo(
               function($criteres) {
                 return (new Class_MoteurRecherche_Result($this->mock_moteur_recherche, $criteres))
                   ->setRecordsQuery('mock select query');
               });

    Class_Codification::setInstance($this->mock_codif);
    Class_MoteurRecherche::setInstance($this->mock_moteur_recherche);
    $this->mock_sql
      ->whenCalled('fetchAllByColumn')
      ->with('mock select query')
      ->answers([ 'D3', 'M1355'])


      ->whenCalled('fetchAll')
      ->with('mock select query', true, false)
      ->answers([ 'D3', 'M1355'])

      ->whenCalled('fetchOne')
      ->with('select libelle from codif_dewey where id_dewey=\'66\'')
      ->answers( 'Generalites')->beStrict();
    $this->mock_sql

      ->whenCalled('fetchOne')
      ->with('select libelle from codif_dewey where id_dewey=\'77\'')
      ->answers('Arts')->beStrict();



    Zend_Registry::set('sql', $this->mock_sql);
  }
}



class RechercheControllerGuideeWithFiltersSelectedTest extends RechercheControllerSearchResultGuideeFixtures {
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/rubrique/D66/facette/A19684', true);
  }


  /** @test */
  public function facettesShouldBeRemovedInRetirerUrl() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/D66')]",
                                      "suppression",$this->_response->getBody());
  }
}




class RechercheControllerWithPanierTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('findAllByRequeteRecherche')
      ->answers([Class_Notice::newInstanceWithId(1,
                                                 ['clef_alpha'=>'COMBAT ORDINAIRE']),
                 Class_Notice::newInstanceWithId(12,
                                                 ['clef_alpha'=>'tarzan'])]);

    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' => ['resultatsimple' => ['liste_nb_par_page' => 1]]]);


    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with("select id_notice, facettes from notices Where notices.clef_alpha in('COMBAT ORDINAIRE', 'BLACKSAD')", true, false)
      ->answers([
                 [1, ''],

                 [12, '']])
      ->beStrict();

    $this->panier_bd = Class_PanierNotice::newInstanceWithId(2,
                                                             ['id_panier' => 1,
                                                              'libelle' => 'Mes BD',
                                                              'date_maj' => '10/02/2011',
                                                              'notices' => 'COMBAT ORDINAIRE;BLACKSAD']);
    $this->dispatch('/recherche/simple/id_panier/2/retour_panier/2', true);
  }


  /** @test */
  public function retourRechercheInitialeShouldLinkToPanierAbonne() {
    $this->assertXPath('//a[contains(@href, "/panier/index/id_panier/2")]');
  }


  /** @test **/
  public function MesBDLibelleShouldBeDisplay() {
    $this->assertXPathContentContains('//span', "Mes BD");
  }


  /** @test */
  public function urlPage2ShouldBeRechercheSimpleWithIdPanerAndRetourAndPage2() {
    $this->assertXPath('//a[contains(@href,"/recherche/simple/id_panier/2/retour_panier/2/page/2")]',
                       $this->_response->getBody());
  }
}



class RechercheControllerSimpleActionWithCatalogueAndDomainBrowserWidgetTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();
    Class_CodifThesaurus::beVolatile();

    $mock_moteur_recherche = Storm_Test_ObjectWrapper::mock();
    $mock_search_result = Storm_Test_ObjectWrapper::mock();
    $mock_moteur_recherche
      ->whenCalled('lancerRecherche')
      ->willDo(
               function($criteres) use ($mock_search_result){
                 $mock_search_result
                   ->whenCalled('getCriteresRecherche')
                   ->answers($criteres);
                 return $mock_search_result;
               });

    $mock_search_result

      ->whenCalled('isError')
      ->answers(false)

      ->whenCalled('getRecordsCount')
      ->answers(10)

      ->whenCalled('getRubrics')
      ->answers([])

      ->whenCalled('getBreadcrumb')
      ->answers([])

      ->whenCalled('fetchRecords')
      ->answers([ $this->notice ])

      ->whenCalled('fetchFacetsAndTags')
      ->answers(['facettes' => [],
                 'tags' => [],
                 'suggests' => []]);

    Class_MoteurRecherche::setInstance($mock_moteur_recherche);

    Class_Profil::getCurrentProfil()
      ->updateModuleConfigAccueil(9,
                                  ['type_module' => 'DOMAIN_BROWSER',
                                   'division' => 1,
                                   'id_module' => 9,
                                   'preferences' => ['display_mode' => Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR,
                                                     'root_domain_id' =>4
                                   ]])
      ->updateModuleConfigAccueil(10,
                                  ['type_module' => 'RSS',
                                   'division' => 1,
                                   'id_module' => 10,
                                  ]);


    $this->fixture('Class_Catalogue',
                   ['id'=>4,
                    'libelle' => 'A',
                    'domaine_parent' => $this->fixture('Class_Catalogue',
                                                       ['id'=>3,
                                                        'libelle' => 'Nouveautés'])]);
  }


  /** @test **/
  public function onRechercheSimpleCatalogue3IdModule9LibelleNouveautesShouldBeDisplay() {
    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9', true);
    $this->assertXPathContentContains('//span[@class="expression-recherche"]',
                                      'Nouveautés');
  }


  /** @test **/
  public function onRechercheSimpleCatalogue3IdModule9OrderByTitreShouldBeOrderByTitle() {
    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9/tri/alpha_titre', true);
    $this->assertXPath('//select[@name="tri"]//option[@value="alpha_titre"][@selected="selected"]');
  }


  /** @test */
  public function onRechercheSimpleCatalogue3IdModule9BreadcrumbShouldBeDisplayed() {
    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9', true);
    $this->assertXPath('//div[@class="domains liste_mur"]//div[@class="breadcrumb"]//a[@href="/"]',
                       $this->_response->getBody());
  }


  /** @test */
  public function onRechercheSimpleCatalogue3IdModule9BreadcrumbPageShouldBeHtml5Valid() {
    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9', true);
    $this->assertHTML5();
  }


  /** @test */
  public function onRechercheSimpleCatalogue3IdModule10BreadcrumbShouldNotBeDisplayed() {
    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/10', true);
    $this->assertNotXPath('//div[@class="domains liste_mur"]//div[@class="breadcrumb"]');
  }
}




class RechercheControllerSimpleActionWithCatalogueAndNoParentsTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();
    Class_CodifThesaurus::beVolatile();

    $mock_moteur_recherche = Storm_Test_ObjectWrapper::mock();
    $mock_moteur_recherche
      ->whenCalled('lancerRecherche')
      ->answers(new Class_MoteurRecherche_Result($mock_moteur_recherche,
                                                 new Class_CriteresRecherche()))
      ->whenCalled('getFacettes')
      ->answers(['facettes' => []]);



    $this->fixture('Class_Catalogue',
                   ['id'=>4,
                    'libelle' => 'A',
                    'domaine_parent' => $this->fixture('Class_Catalogue',
                                                       ['id'=>3,
                                                        'libelle' => 'Nouveautés'])]);

    $this->dispatch('/recherche/simple/id_catalogue/3', true);
  }


  /** @test **/
  public function catalogueLibelleShouldBeDisplay() {
    $this->assertXPathContentContains('//span[@class="expression-recherche"]', "Nouveautés",$this->_response->getBody());
  }


  /** @test */
  public function catalogueBreadcrumbShouldNotDisplay() {
    $this->assertNotXPath('//div[@class="liste_mur breadcrumb_domains"]');
  }
}



class RechercheControllerActionSimpleWithResetTest extends RechercheControllerNoticeTestCase {
  /** @test */
  public function responseShouldRedirectToActionSaisie() {
    $this->dispatch('/recherche/simple/statut/reset', true);
    $this->assertRedirectTo('/opac/recherche/saisie');
  }
}






class RechercheControllerGuideeThesaurusTest extends  RechercheControllerGuideeHomePageTest {
  public function setUp() {
    parent::setUp();

    $this->mock_sql = Storm_Test_ObjectWrapper::mock();

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_CodifThesaurus')
      ->whenCalled('findByIdOrigineAndCode')
      ->answers([Class_CodifThesaurus::newInstanceWithId(59, ['id_thesaurus'=>'59','libelle' => 'Generalites','libelle_facette'=>null])])
      ->whenCalled('findFirstBy')
      ->answers(Class_CodifThesaurus::newInstanceWithId(59, ['id_thesaurus'=>'59','libelle' => 'Generalites','libelle_facette'=>null]))
      ;

    Zend_Registry::set('sql', $this->mock_sql);
    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with('select * from codif_dewey where LENGTH(id_dewey)=1 order by id_dewey')
      ->answers([ ['id_dewey'=>66,
                   'libelle' => 'Generalites',
                   'nb_notices'=>1],
                 ['id_dewey'=>77,
                  'libelle' => 'Arts',
                  'nb_notices' => 0]]
      )->beStrict();

    $this->mock_sql
      ->whenCalled('fetchOne')
      ->with('select libelle from codif_thesaurus where id_thesaurus=\'59\'')
      ->answers( 'Generalites');

    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' => ['resultatsimple' => [
                                                            'liste_format' => $this->_liste_format ,
                                                            'liste_codes' => "TANECRH"]]])
      ->setSelTypeDoc('1;2;3;4;5');

    $this->dispatch('/recherche/simple/rubrique/H59', true);


  }


  /** @test */
  public function generaliteThesaurusShouldBeDisplayed() {
    $this->assertXPathContentContains("//a[contains(@href,'recherche/simple/rubrique/H59')]",
                                      'Generalites',
                                      $this->_response->getBody());
  }
}




class RechercheControllerAjoutNoticePanierUrlWithMurConfigTest extends RechercheControllerSimpleActionListeFormatTestCase {
  protected $_liste_format = Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR;

  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
    ZendAfi_Auth::getInstance()->clearIdentity();
    Class_Profil::getCurrentProfil()->setCfgModules([]);

    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/alpha_auteur/ajoutPanier/702167',true);

  }

  /** @test */
  public function pommeShouldBePresentInRedirectedPageAsResultatInSession() {
    $this->assertXPathContentContains('//div', 'pomme');
  }

  /** @test */
  public function correctPunctuationSpacesShouldBeDisplayed() {
    $this->assertXPathContentContains('//span',"pour : ");
  }

  /** @test */
  public function pageShouldContainsLinkToSuggestionAchats() {
    $this->assertXPathContentContains('//a[contains(@href, "/abonne/suggestion-achat")]',
                                      'Suggérer un achat');
  }


  /** @test */
  public function selectedTriShouldBeAlphaAuteur() {
    $this->assertXPath('//select[@name="tri"]//option[@value="alpha_auteur"][@selected="selected"]');

  }

  /** @test */
  public function withOutLoggedUserPopupLoginShouldBeInitialized() {
    $this->assertXPathContentContains('//script', 'initializePopups');
  }


  /** @test */
  public function linksAjoutPanierShouldHaveDataPopupTrue() {
    $this->assertXPath('//a[contains(@href, "/panier/ajout-ajax/id_notice/")][@data-popup="true"]',$this->_response->getBody());
  }


  /** @test **/
  public function permalinkShouldBeDisplay() {
    $this->assertXPathContentContains('//span', "recherche/viewnotice/expressionRecherche/potter/facettes/T1/facette/B1/page/2/clef/PETITESSCENESDEBALCONTERRASSE-SUIVIDE100PLANTESPO---RUSTICA-2009-1/id/42225?id_profil=2",$this->_response->getBody());
  }
}




class RechercheControllerNavigationTest extends RechercheControllerNoticeTestCase {
  public function setUp(){
    parent::setUp();

    $batman = Class_Notice::newInstanceWithId(1,
                                              ['clef_alpha'=>'batman']);
    $tarzan = Class_Notice::newInstanceWithId(12,
                                              ['clef_alpha'=>'tarzan']);
    $batman = Class_Notice::newInstanceWithId(28,
                                              ['clef_alpha'=>'musso']);
    $tarzan = Class_Notice::newInstanceWithId(99,
                                              ['clef_alpha'=>'lesarbres']);


    $this->mock_sql = $this->mock()
                           ->whenCalled('fetchAll')
                           ->with('select id_notice, facettes from notices order by alpha_titre', true, false)
                           ->answers([
                                      [28, ''],
                                      [12, ''],
                                      [345, ''],
                                      [1, ''],
                                      [99, '']
                                      ]
                           )
                           ->beStrict();

    Zend_Registry::set('sql', $this->mock_sql);

    Storm_Test_ObjectWrapper::onLoaderOfModel('Class_Notice')
      ->whenCalled('getNoticeIdsByRequeteRecherche')
      ->with('Select id_notice from notices order by alpha_titre')
      ->answers([28,12,345,1,99]);
  }

  /** @test */
  public function navigationSuivantShouldRedirectToBatmanViewnotice() {
    $this->dispatch('/recherche/viewnotice/id/345/tri/alpha_titre/navigation/suivant',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/1/tri/alpha_titre/clef/batman|');
  }


  /** @test */
  public function navigationPrecedentShouldRedirectToTarzanViewnotice() {
    $this->dispatch('/recherche/viewnotice/id/345/tri/alpha_titre/navigation/precedent',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/12/tri/alpha_titre/clef/tarzan|');
  }

  /** @test */
  public function navigationPrecedentOnTheFirstNoticeMussoOfResultatRechercheShouldRedirectToMusso() {
    $this->dispatch('/recherche/viewnotice/id/28/tri/alpha_titre/navigation/precedent',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/28/tri/alpha_titre/clef/musso|');
  }


  /** @test */
  public function navigationSuivantOnTheLastNoticeLesArbresOfResultatRechercheShouldRedirectToLesarbres() {
    $this->dispatch('/recherche/viewnotice/id/99/tri/alpha_titre/navigation/suivant',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/99/tri/alpha_titre/clef/lesarbres|');
  }


  /** @test */
  public function navigationSuivantOnTheFirstNoticeMussoOfResultatRechercheShouldRedirectToTarzan() {
    $this->dispatch('/recherche/viewnotice/id/28/tri/alpha_titre/navigation/suivant',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/12/tri/alpha_titre/clef/tarzan|');
  }


  /** @test */
  public function navigationPrecedentOnTheLastNoticeLesarbresOfResultatRechercheShouldRedirectToBatman() {
    $this->dispatch('/recherche/viewnotice/id/99/tri/alpha_titre/navigation/precedent',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/1/tri/alpha_titre/clef/batman|');
  }


  /** @test */
  public function navigationSuivantOnNoticeLesarbresWhenResultatRechercheIsEmptyShouldRedirectToCurrentNoticeLsearbres() {
    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with('select id_notice, facettes from notices order by alpha_titre', true, false)
      ->answers([]);


    $this->dispatch('/recherche/viewnotice/id/99/tri/alpha_titre/navigation/suivant',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/99/tri/alpha_titre/clef/lesarbres|');
  }


  /** @test */
  public function navigationSuivantOnNoticeLesarbresWhenResultatRechercheAsMussoResultShouldRedirectToCurrentNoticeMusso() {
    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with('select id_notice, facettes from notices order by alpha_titre', true, false)
      ->answers([ [28, '' ] ]);

    $this->dispatch('/recherche/viewnotice/id/28/tri/alpha_titre/navigation/suivant',true);
    $this->assertRedirectRegex('|/recherche/viewnotice/id/28/tri/alpha_titre/clef/musso|');
  }

}




class RechercheControllerAvanceeTest extends AbstractControllerTestCase {
  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/avancee', true);
  }


  /** @test */
  public function formActionShouldBeRechercheSimple() {
    $this->assertXPath('//form[@action="/recherche/simple"]');
  }


  /** @test **/
  public function formShouldContainTagListCocheGenre() {
    $this->assertXPath('//form//input[@id="genre"][following-sibling::div[@class="tag_selection"]]');
  }


  /** @test **/
  public function scriptControlMajShouldNotBePresent() {
    $this->assertNotXPath('//script[contains(@src,"controle_maj")]');
  }


  /** @test **/
  public function scriptTagSlectionShouldBePresent() {
    $this->assertXPath('//script[contains(@src,"/admin/js/tag_selection")]');
  }
}



class RechercheControllerViewNoticeWhichIsInMyPanier extends RechercheControllerNoticeTestCase {

  public function setup() {
    parent::setup();

    $this->user = Class_Users::newInstanceWithId(23, ['pseudo' => 'Pioup',
                                                      'nom' => 'Jojo',
                                                      'login' => 'Super',
                                                      'password' => '123789']);

    $this->user->save();
    ZendAfi_Auth::getInstance()->logUser($this->user);

    $this->panier_bd = Class_PanierNotice::newInstanceWithId(2,
                                                             ['id_panier' => 1,
                                                              'libelle' => 'Mes BD',
                                                              'date_maj' => '10/02/2011',
                                                              'notices' => 'POMME;POIRE',
                                                              'user' => $this->user]);
    $this->panier_bd->save();

    $this->panier_bd_2 = Class_PanierNotice::newInstanceWithId(3,
                                                               ['id_panier' => 1,
                                                                'libelle' => 'Mes BD 2',
                                                                'date_maj' => '10/02/2011',
                                                                'notices' => 'POIRE',
                                                                'user' => $this->user]);
    $this->panier_bd_2->save();

    $pomme = Class_Notice::newInstanceWithId(10,
                                             ['titre_principal' => 'Le combat des pommes',
                                              'clef_alpha' => 'POMME',
                                              'date_creation' => '2010-01']);

    $poire = Class_Notice::newInstanceWithId(12, ['titre_principal' => 'Le combat des poires',
                                                  'clef_alpha' => 'POIRE',
                                                  'date_creation' => '2010-01']);



    $this->panier_loader = Storm_Test_ObjectWrapper::onLoaderOfModel('Class_PanierNotice')
      ->whenCalled('save')->answers(true)
      ->whenCalled('delete')->answers(true)

      ->whenCalled('findAll')->answers([$this->panier_bd])

      ->whenCalled('findAllBy')
      ->with(['role' => 'user', 'model' => $this->user])
      ->answers([$this->panier_bd]);


  }


  /** @test **/
  public function viewNoticePommeShouldContainsLinkAddToPanier() {
    $this->dispatch('recherche/viewnotice/id/10',true);
    $this->assertXpath('//div[@class="navigation"]/a[@class="panier dans_panier"]',$this->_response->getBody());
  }


  /** @test **/
  public function viewnoticeLinkAddToPanierTitleShouldBeDansBd() {
    $this->dispatch('recherche/viewnotice/id/10',true);
    $this->assertXpath('//div[@class="navigation"]/a[@class="panier dans_panier"][@title="Dans le panier Mes BD"]',$this->_response->getBody());
  }


  /** @test **/
  public function viewNoticePommeShouldContainsTagDansPanierBd() {
    $this->dispatch('recherche/viewnotice/id/10',true);
    $this->assertXpath('//div[@class="flags_notice"]/span[@class="dans_panier"][@title="Dans le panier Mes BD"]',$this->_response->getBody());
  }


  /** @test **/
  public function viewNoticePoireShouldContainsTagDansPanierBdEtBd2() {
    $this->dispatch('recherche/viewnotice/id/12',true);
    $this->assertXpath('//div[@class="flags_notice"]/span[@class="dans_panier"][@title="Dans les paniers Mes BD 2 - Mes BD"]',$this->_response->getBody());
  }


  /** @test **/
  public function withOutLoggedUserFlagsNoticeShouldNotContainsDansPanier() {
    ZendAfi_Auth::getInstance()->clearIdentity();
    $this->dispatch('recherche/viewnotice/id/12',true);
    $this->assertNotXpath('//div[@class="flags_notice"]/span[@class="dans_panier"]',$this->_response->getBody());
  }

}



class RechercheControllerSimpleActionWithCvsActivatedTest extends RechercheControllerSimpleActionTestCase {

  protected $_cvs;

  public function setUp() {
    parent::setUp();
    $this->dispatch('/recherche/simple/expressionRecherche/potter/facettes/T1/facette/B1/page/2', true);
    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' =>
                       ['resultatsimple' => [ 'cvs_autres_resultats' => 'Results from opac',
                                             'cvs_resultat_titre' => 'CVS Ressources',
                                             'cvs_nb_result' => '5',
                                             'cvs_display_position' => '1']]]);

    RessourcesNumeriquesFixtures::activateCVS();
    $group_cvs = $this->fixture('Class_UserGroup', ['id' => 20 ,
                                                    'libelle' => 'CVS acces'])
                      ->addRight(Class_UserGroup::RIGHT_ACCES_CVS);

    $polo = $this->fixture('Class_Users', ['id' => 15,
                                           'login' => 'polo',
                                           'password' => '456',
                                           'pseudo' => 'polo',
                                           'date_fin' => '2025-04-26'])
                 ->beAbonneSIGB()
                 ->setUserGroups([$group_cvs]);

    ZendAfi_Auth::getInstance()->logUser($polo);
    $record = $this->fixture('Class_Notice',['id'=> 10,
                                             'titre_principal' => 'Le photographe',
                                             'auteur_principal' => 'Guibert']);
    $this->_cvs = Class_CVSLink::forUser($record);
    $http_client = Storm_Test_ObjectWrapper::mock();

    Class_CVSLink::setDefaultHttpClient($http_client);
    Class_Xml::setDefaultHttpClient($http_client);
    RessourcesNumeriquesFixtures::activateCVS();

    $http_client
      ->whenCalled('postData')
      ->answers($this->_returnedXML());

    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/alpha_auteur',true);

  }

  protected function _returnedXML() {
    $xml = file_get_contents(realpath(dirname(__FILE__)). '/../../../../fixtures/cvs_search_ecole.xml');
    return $xml;
  }

  /** @test **/
  public function titleResultFromOpacShouldBeDiplay() {
    $this->assertXPathContentContains('//h1','Results from opac');
  }


  /** @test */
  public function simpleContentShouldContainsCVSDiv() {
    $this->assertXPath('//div[@class="conteneur_simple"]//div[contains(@class,"cvs_container")]', $this->_response->getBody());
  }


  /** @test **/
  public function cvsBoiteShouldHaveTitreCVSRessources() {
    $this->assertXPathContentContains('//div[@class="conteneur_simple"]//div[contains(@class,"cvs_container")]//h1', 'CVS Ressources', $this->_response->getBody());
  }

  /** @test **/
  public function cvsBoiteClassShouldHavePosition1() {
    $this->assertXPath('//div[@class="conteneur_simple"]//div[@class="cvs_container position_1"]', $this->_response->getBody());
  }
}



class RechercheControllerSimpleActionWithCvsActivatedAndPreferencesHiddenTest extends RechercheControllerSimpleActionTestCase {
  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' =>
                       ['resultatsimple' => [ 'cvs_display_position' => '0']]]);
    $zork = $this->fixture('Class_Users',
                           ['id' => 4,
                            'login' => 'zork_sigb',
                            'role_level' => 2,
                            'idabon' => '98475',
                            'id_site' => 2,
                            'password' => 'xzy']);
    $group_multimedia = $this->fixture('Class_UserGroup',
                                       ['id' => 20,
                                        'libelle' => 'Multimedia'])
                             ->addRight(Class_UserGroup::RIGHT_ACCES_CVS);


    $zork->beAbonneSIGB()
         ->setUserGroups([$this->group_multimedia])
         ->save();
    ZendAfi_Auth::getInstance()->logUser($zork);
    RessourcesNumeriquesFixtures::activateCVS();

    $this->dispatch('/recherche/simple/expressionRecherche/pomme/tri/alpha_auteur',true);

  }


  /** @test */
  public function simpleContentShouldNotContainsCVSDiv() {
    $this->assertNotXPath('//div[@class="conteneur_simple"]//div[contains(@class,"cvs_container")]');
  }

}



class RechercheControllerSuggestAjaxActionTest extends RechercheControllerNoticeTestCase {
  /** @test */
  public function suggestForHarryPotterShouldNotBeEmpty() {
    Class_Autocomplete_Index::setSearcher(
                                          $this->mock()
                                          ->whenCalled('search')->answers(['Harry à la plage']));

    $this->dispatch('/opac/recherche/suggestajax/startsWith/harry+potter', true);
    $response = json_decode($this->_response->getBody());
    $this->assertFalse(empty($response));
  }
}




class RechercheController_IndexSearcherTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    Class_Notice::beVolatile();
  }


  protected function searchFor($terms) {
    Class_Autocomplete_Index::setSearcher((new Class_Autocomplete_IndexSearcher())
                                          ->setBasePath(ROOT_PATH.'tests/library/Class/Autocomplete/index/'));

    $this->dispatch('/opac/recherche/suggestajax/startsWith/'.$terms, true);
    $results = json_decode($this->_response->getBody());
    if (!empty($results)) {
      return $results[0]->label;
    }

    return NULL;
  }


  public function searches() {
    return [
            ["<span>L'île</span> <span>de</span> <span>maïté</span>", "l'ile dE Maite"],
            ['<span>Jean-P</span>ierre Cuq','jean-p'],
            ["L'<span>île</span> de <span>maïté</span>", "ile maite"],
            ["Dis-moi la <span>vérité</span>.", "verite"],
            ["<span>Ô</span> Mireille si tu savais, <span>où</span> je suis.", 'o ou'],
            ["Centre interdépartemental de gestion de la Petite couronne de la région <span>d'Ile</span>-de-France", "d'ile"],
            ['Jacques <span>Réda</span>', 'reda'],
            ['<span>First</span> impressions de The <span>Strokes</span>', 'first strokes'],
            ['Association <span>Ville</span><span>pa</span>risis et son <span>pa</span>ssé', 'ville pa'],
            ['<span>Harry</span> <span>Potter</span> et le prisonnier d\'Azkaban de Joanne Kathleen Rowling.', 'harry potter'],
            ['<span>Etoile</span> d\'amour', 'étoile'],
    ];
  }

  /** @test
   *  @dataProvider searches()
   */
  public function autocompleteTermShouldBeFound($expected_result, $search_expression) {
//    echo (new Class_Autocomplete_IndexSearcher)->buildGrepCommand($search_expression)."\n";
    $this->assertEquals(
                        $expected_result,
                        $this->searchFor($search_expression));
  }


  /** @test */
  public function grepCommandForIleMaiteShouldRestrictLastResultToTen() {
    $this->assertEquals(
                        "grep -ri -E --no-filename '(\b|'\'')M[aàáâãäå][iìíîï]t[eèéêë]' | sort --unique | grep -i -E '(\b|'\'')l'\''[iìíîï]l[eèéêë]' | grep -i -E '(\b|'\'')[iìíîï]l[eèéêë]' | grep -m 10 -i -E '(\b|'\'')d[eèéêë]'",
                        (new Class_Autocomplete_IndexSearcher)->buildGrepCommand("l'ile dE Maite"));
  }


  /** @test */
  public function envLocaleShouldBeForcedToCurrentLocale() {
    putenv('LANG=en_EN');
    setlocale('LC_ALL', 'en');
    $this->dispatch('/opac/recherche/suggestajax/startsWith/verite/language/fr', true);
    $this->assertEquals("Dis-moi la <span>vérité</span>.", $this->searchFor('verite'));
    $this->assertEquals('UTF-8', exec('locale charmap'));
  }
}



class RechercheControllerViewnoticeWithPreferencesFromOtheProfile extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $target_pref = ['entete' => 'N'];
    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' => ['viewnotice1' => $target_pref]])
      ->save();

    $locale_pref = ['entete' => 'A'];
    $this->fixture('Class_Profil',
                   ['id' => 15])
         ->setCfgModules(['recherche' => ['viewnotice1' => $locale_pref]]);

    $this->dispatch('/opac/recherche/viewnotice/id_profil/15/id_module/2-4/id/345/id_catalogue/8', true);
  }


  /** @test */
  public function docTypeShouldBePresent() {
    $this->assertXPathContentContains('//div[@class="entete_notice"]//dd', '2002',
                                      $this->_response->getBody());
  }


  /** @test */
  public function authorShouldNotBePresent() {
    $this->assertNotXPathContentContains('//div[@class="entete_notice"]//a', 'Bernard Génin');
  }


  /** @test */
  public function backLinkShouldContainsIdCatalog() {
    $this->assertXPath('//a[@class="retour"][contains(@href, "id_catalogue/8")]');
  }
}



abstract class RechercheControllerViewnoticeWithBreadcrumbTestCase extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    Class_Profil::getCurrentProfil()
      ->setBarreNavOn(true);
    }
}



class RechercheControllerViewnoticeWithBreadcrumbAndParamsTest extends RechercheControllerViewnoticeWithBreadcrumbTestCase {
  /** @test */
  public function breadcrumbShouldContainsMyTitle() {
    $this->dispatch('recherche/viewnotice/id/345/titre/my-title', true);
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span', 'my-title');
  }


  /** @test */
  public function breadcrumbWithRubriqueShouldDisplayRechercheGuidee() {
    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with("select * from codif_dewey where id_dewey like '2%' and LENGTH(id_dewey)=2 order by id_dewey")
      ->answers([]);

    $this->dispatch('recherche/viewnotice/id/345/rubrique/D2', true);
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span', 'Recherche guidée');
  }
}




class RechercheControllerViewnoticeWithBreadcrumbAndIdModuleParamTest extends RechercheControllerViewnoticeWithBreadcrumbTestCase {
  public function setUp() {
    parent::setUp();

    $profil = $this->fixture('Class_Profil', ['id' => 18]);
    $profil->setCfgAccueil(['modules' => ['8' => ['division' => 1,
                                                  'type_module' => 'KIOSQUE',
                                                  'preferences' => ['titre' => 'my kiosk']]]])
           ->save();

    $this->dispatch('recherche/viewnotice/id/345/id_module/18-8', true);
  }


  /** @test */
  public function breadcrumbShouldContainsMyKiosk() {
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span', 'my kiosk');
  }


    /** @test */
  public function breadcrumbShouldContainsMainTitle() {
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span[3]', 'Cinéma d\'animation');
  }


  /** @test */
  public function titlePageShouldBeAsExpected() {
    $this->assertXPathContentContains('//title', '- my kiosk - Cinéma d\'animation');
  }

}



class RechercheControllerViewnoticeWithBreadcrumbAndIdCatalogueParamTest extends RechercheControllerViewnoticeWithBreadcrumbTestCase {
  public function setUp() {
    parent::setUp();

    $this->fixture('Class_Catalogue',
                   ['id'=> 2,
                    'libelle' => 'my catalogue']);

    $this->dispatch('recherche/viewnotice/id/345/id_catalogue/2', true);
  }


  /** @test */
  public function breadcrumbShouldContainsMyCatalogue() {
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span', 'my catalogue');
  }
}



class RechercheControllerViewnoticeWithBreadcrumbAndIdPanierParamTest extends RechercheControllerViewnoticeWithBreadcrumbTestCase {
  public function setUp() {
    parent::setUp();
    $this->fixture('Class_PanierNotice',
                   ['id'=> 2,
                    'libelle' => 'my panier']);

    $this->dispatch('recherche/viewnotice/id/345/id_panier/2', true);
  }


  /** @test */
  public function breadcrumbShouldContainsMyPanier() {
    $this->assertXPathContentContains('//div[@class="barre_nav"]//span', 'my panier');
  }


  /** @test */
  public function pageTitleShouldBeAsExpected() {
    $this->assertXPathContentContains('//head', 'my panier - Cinéma d\'animation', $this->_response->getBody());
  }
}



class RechercheControlleSimpleActionWithEmptyDomainSettingsTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $this->fixture('Class_Catalogue',
                   ['id'=>3,
                    'libelle' => 'Nouveautés',
                    'auteur' => 'Paul']);
    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9/aleatoire/1', true);
  }


  /** @test */
  public function onRechercheSimpleCatalogue3IdModule9ResultsShouldBeEmpty() {
    $this->assertXPathContentContains('//div[@class="info-recherche"]', 'Aucun résultat trouvé',                       $this->_response->getBody());
  }
}



class RechercheControlleSimpleActionWithEmptyDomainSettingsAndSiteLinkedTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();
    $this->fixture('Class_Catalogue',
                   ['id'=>3,
                    'libelle' => 'Nouveautés']);
    $this->fixture('Class_Sitotheque',
                   ['id' => 1,
                    'titre' => 'Mon lien',
                    'url' => 'http://monlien.com',
                    'domaine_ids' => 3,
                   ]);

    Class_Sitotheque::find(1)->index();

    $this->mock_sql
      ->whenCalled('fetchAll')
      ->with("select id_notice, facettes from notices Where MATCH(facettes) AGAINST('Q3' IN BOOLEAN MODE) order by annee desc", true, false)
      ->answers([  [1, ''] ])
      ->whenCalled('fetchOne')
      ->answers(1)
      ->whenCalled('fetchAll')
      ->answers([Class_Notice::find(1)->toArray()])
      ->beStrict();


    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' =>
                       ['resultatsimple' =>
                        ['liste_format' =>  Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR]]]);

    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9/aleatoire/1', true);
  }


  /** @test */
  public function monLienShouldExistsAsANotice() {
    $this->assertEquals('MON LIEN', Class_Notice::find(1)->getAlphaTitre());
  }


  /** @test */
  public function sitoDomainEShouldExists() {
    $this->assertNotNull(Class_NoticeDomain::find(1));
  }


  /** @test */
  public function onRechercheSimpleCatalogueSitoShouldBePresent() {
    $this->assertXPathContentContains('//div[@class="resultat_recherche"]//a', 'Mon lien',                       $this->_response->getBody());
  }
}



class RechercheControlleSimpleActionWithEmptyDomainSettingsAndArticlesLinkedTest extends RechercheControllerNoticeTestCase {
  public function setUp() {
    parent::setUp();

    $this->fixture('Class_Catalogue',
                   ['id'=>3,
                    'libelle' => 'News']);
    $this->fixture('Class_Article',
                   ['id' => 1,
                    'titre' => 'News of the sprint',
                    'id_user' => 1,
                    'indexation' => 1,
                    'contenu' => 'Articles are going to be auto indexed !',
                    'domaine_ids' => '3']);

    Class_Article::find(1)->index();

    $this->mock_sql
                     ->whenCalled('fetchAll')
                     ->with("select id_notice, facettes from notices Where MATCH(facettes) AGAINST('Q3' IN BOOLEAN MODE) order by annee desc", true, false)
                     ->answers([  [1, ''] ])

                     ->whenCalled('fetchOne')
                     ->answers(1)
                     ->whenCalled('fetchAll')
                     ->answers([Class_Notice::find(1)->toArray()])
                     ->beStrict();


    Class_Profil::getCurrentProfil()
      ->setCfgModules(['recherche' =>
                       ['resultatsimple' =>
                        ['liste_format' =>  Class_Systeme_ModulesAppli::LISTE_FORMAT_MUR]]]);

    $this->dispatch('/recherche/simple/id_catalogue/3/id_module/9/aleatoire/1', true);
  }


  /** @test */
  public function newsOfTheSPrintShouldExistsAsANotice() {
    $this->assertNotNull(Class_Notice::find(1));
  }


  /** @test */
  public function noticeAuthorShouldBeAsExpected() {
    $this->assertEquals('', Class_Notice::find(1)->getAuteurPrincipal());
  }


  /** @test */
  public function newsOfTheSprintDomainShouldExists() {
    $this->assertNotNull(Class_NoticeDomain::find(1));
  }


  /** @test */
  public function searchOnNewsShouldContainsNewsOfTheSprint() {
    $this->assertXPathContentContains('//div[@class="resultat_recherche"]//a', 'News of the sprint');
  }
}

?>