<?php

class PhoneBookCtrl extends Ctrl {



	public function reload() {
		$index = new Index();
		$index->add($this->show());
		return $index;
	}



	public function show() {
		RequestSetupFilter::savepoint('PhoneBook/PhoneBookCtrl/reload'); // after page reload this method will generate its content

		$v = new View('MainView'); // this view replaces 'MainView' previously displayed by LoginCtrl::show()
		$v->template = 'app/PhoneBook/List.tpl';
		$v->setEffect(new FadeInEffect());

		$phonesList = ActionService::execAction('PhoneBook/PhonesListCtrl/show');
		$v->add($phonesList, 'list');

		$new = new Button('newButton');
		$new->text = __('new');
		$new->addListener(new ClickListener(new Action('PhoneBook/FormCtrl/open')));
		$v->add($new);

		$edit = new Button('editButton');
		$edit->text = __('edit');
		$edit->addListener(new ClickListener(new Action('PhoneBook/FormCtrl/open', $phonesList->valueReader())));
		$v->add($edit);

		$lang = new Select('language-selector');
		$lang->options = array('en_EN' => 'English', 'pl_PL' => 'Polski');
		$lang->value = i18n::getLang();
		$lang->addListener(new ChangeListener(new Action('PhoneBook/PhoneBookCtrl/setLang', $lang->valueReader())));
		$v->add($lang, 'lang');

		$v->add(new Label('preview'));

		return $v;
	}



	public function getPreview($id) {
		$v = new View('preview');
		$v->template = 'app/PhoneBook/Preview.tpl';

		require_once 'PhonesListCtrl.class.php';
		$plc = new PhonesListCtrl();
		$ds = $plc->getDataSource();
		foreach ($ds->fetch() as $entry) {
			if ($entry['id'] != $id) {
				continue;
			}
			$v->name = $entry['name'];
			$v->phone = $entry['phone'];
		}

		return $v;
	}



	public function reorder($targetId, $sourceId) {
		$source = new PhoneBookEntry();
		$source->loadById($sourceId);
		$target = new PhoneBookEntry();
		$target->loadById($targetId);
		
		$source->id = '-1';
		$source->save();
		$target->id = $sourceId;
		$target->save();
		$source->id = $targetId;
		$source->save();

		return ActionService::execAction('PhoneBook/PhonesListCtrl/show');
	}



	public function setLang($lang) {
		i18n::setLang($lang);
		return $this->show();
	}



} // class PhoneBookCtrl

?>