<?php
// src/AppBundle/Admin/CompagnyAdmin.php
namespace AppBundle\Admin;

use Sonata\AdminBundle\Admin\AbstractAdmin;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Form\FormMapper;

use Oh\GoogleMapFormTypeBundle\Form\Type\GoogleMapType;

class CompagnyAdmin extends AbstractAdmin
{
	//configure which fields are displayed on the edit and create actions. 
	//The FormMapper behaves similar to the FormBuilder of the Symfony Form component;
    protected function configureFormFields(FormMapper $formMapper)
    {
        $formMapper
		->with('Informations Principales', array(
                    'class'       => 'col-md-6',
                    'box_class'   => 'box box-solid',
                    'description' => '',
                ));
			
			$formMapper->add('name', 'text');
			$formMapper->add('created');
			$formMapper->add('sector','entity', array(
				'class' => 'AppBundle\Entity\Sector',
				'choice_label' => 'name',
			));
			$formMapper->add('canton','entity', array(
				'class' => 'AppBundle\Entity\Canton',
				'choice_label' => 'name',
			));
		  
			$formMapper->add('phone');
			$formMapper->add('director');
			$formMapper->add('activity');
			$formMapper->add('partner');
			$formMapper->add('member');
			$formMapper->add('logo', 'sonata_type_model', array(
				'property' => 'alt',
				'template' => 'appBundle:FieldType:imageChoiceField.html.twig',
				'btn_delete' => false,
				'required' => false)
			)->end();
    	$formMapper->with('Localisation', array(
                    'class'       => 'col-md-6',
                    'box_class'   => 'box box-solid location-box',
                    'description' => '',
                ))
				//->add('location_adresse')
				->add('street')
				->add('number')
				->add('zip')
				->add('city')
				->add('latlng', GoogleMapType::class, array(
				'label' 		 => 'Posistion sur google map',
				'map_width'      => '100%',     // the width of the map
				'map_height'     => '350px',     // the height of the map
				'default_lat'    => 46.2043907,    // the starting position on the map
				'default_lng'    => 6.143157699, // the starting position on the map
				))
		->end();
		$formMapper->with('Effectifs', array(
                    'class'       => 'col-md-3',
                    'box_class'   => 'box box-solid',
                    'description' => '',
                ));
				//->add('location_adresse')
				$formMapper->add('effective','text',array('label'=>'valeur exacte', 'required'=>false ));
			$formMapper->add('effective_aprox','choice',array('label'=>'ou par tranche (en cas d\'incertitude)','choices' => 
					array(
							'1 à 9'		 => '1 à 9',
							'10 à 49'	 => '10 à 49',
							'50 à 249'		 => '50 à 249',
							'250 ou plus'	 => '250 ou plus',
					 ),
					 'required'=>false,
					 'mapped'=>false
			))
			
		->end();
		$formMapper->with('Sites internet', array(
                    'class'       => 'col-md-3',
                    'box_class'   => 'box box-solid',
                    'description' => '',
                ));
			$formMapper->add('website');
			$formMapper->add('website_2')
		->end();
    }

	// This method configures the filters, used to filter and sort the list of models;
    protected function configureDatagridFilters(DatagridMapper $datagridMapper)
    {
       $datagridMapper->add('id');
	   $datagridMapper->add('name');
       $datagridMapper->add('zip');
       $datagridMapper->add('city');
    }
	//Here you specify which fields are shown when all models are listed 
	//(the addIdentifier() method means that this field will link to the show/edit page of this particular model).
    protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
			->add('id')
			->addIdentifier('name','string', array('label'=>'Nom'))
			->add('location_adresse','string', array('label'=>'Adresse'))
			->add('city');
    }
	
	public function toString($object)
    {
        return ($object->getName()!=null)
            ? $object->getName()
            : 'Entreprise'; // shown in the breadcrumb on the create view
    }
	
	/*
	*  PRE PERSIST
	*/
	public function prePersist($company)
    {
        $this->manageEmbeddedImageAdmins($company);
    }
	/*
	*  PRE UPDATE
	*/
    public function preUpdate($company)
    {
        $this->manageEmbeddedImageAdmins($company);
    }
	

    private function manageEmbeddedImageAdmins($company)
    {
		if(!$this->getForm()->get('effective')->getData()){
			$company->setEffective($this->getForm()->get('effective_aprox')->getData());//$this->getFormFieldDescriptions('effective_aprox'));
		}
        // Cycle through each field
        foreach ($this->getFormFieldDescriptions() as $fieldName => $fieldDescription) {
            // detect embedded Admins that manage Images
            if ($fieldDescription->getType() === 'sonata_type_admin' &&
                ($associationMapping = $fieldDescription->getAssociationMapping()) &&
                $associationMapping['targetEntity'] === 'AppBundle\Entity\Image'
            ) {
                $getter = 'get'.$fieldName;
                $setter = 'set'.$fieldName;

                /** @var Image $image */
                $image = $company->$getter();

                if ($image) {
                    if ($image->getFile()) {
                        // update the Image to trigger file management
                        $image->refreshUpdated();
                    } elseif (!$image->getFile() && !$image->getUrl()) {
                        // prevent Sf/Sonata trying to create and persist an empty Image
                        $company->$setter(null);
                    }
                }
            }
        }
    }

	
}
?>