<?php

class LanguageChooser extends Widget {
        static $title = "Language Chooser";
        static $cmsTitle = "Language Chooser";
        static $description = "Allows you to choose your language";

        static $db = array("ShowCurrent" => "Boolean");
        static $defaults = array('ShowCurrent' => false);

        function getCMSFields(){
                return new FieldSet(new CheckboxField('ShowCurrent', _t('LanguageChooser.SHOWCURRENT', 'Show current language')));
        }

        function Chooser() {
		if(!Controller::currentController()) {
			return;
		}
                $langs = i18n::get_existing_content_languages();
                $data = new DataObjectSet();
                foreach(array_keys($langs) as $code) {
                        if($code == Translatable::current_lang() && !$this->ShowCurrent) {
                                continue;
                        }
                        $page = Translatable::get_one_by_lang("SiteTree", $code, "`SiteTree`.ID = " . Controller::currentController()->ID);
                        if(!$page) {
                                $data->push(new ArrayData(array('name' => i18n::get_language_name($code, true), 'link' => Director::protocolAndHost() . Director::baseURL() . '?lang=' . $code)));
                        } else {
                                $data->push(new ArrayData(array('name' => i18n::get_language_name($code, true), 'link' => Director::protocolAndHost() . Director::baseURL() . $page->URLSegment . '?lang=' . $code)));
                        }
                }
                return $data;
        }

        function WidgetHolder() {
                if(count(i18n::get_existing_content_languages()) > 1) {
                        return $this->renderWith("WidgetHolder");
                }
                return "";
        }
}

