class Admin::TranslationsController < ApplicationController

  layout "admin"
  before_filter :authenticate_user!
  before_filter :is_admin?
  
  def index
    set_variables
  end
  
  def edit
    set_variables
  end
  
  # Update either the i18n_variables or the languages
  def update
    begin
      case params[:id]
        # Update the i18n_variables
        when 'all'
          params[:i18n_variables].each do |id, var|
            i18n_variable = I18nVariable.find(id)
            i18n_variable.update_attributes(var)
          end
        # Add a language
        when 'add'
          site = Site.find(session[:site])
          if !site.valid_locales.include?(params[:language])
            site.valid_locales << params[:language] 
            site.save
            I18nVariable.create({:key => params[:language], :document_class => 'language'})
          end
        # Enable a language
        when 'enable'
          site = Site.find(session[:site])
          if !site.in_use_locales.include?(params[:enable_language])
            site.in_use_locales << params[:enable_language]
            site.save
          end
        # Disable a language
        when 'disable'
          site = Site.find(session[:site])
          if site.in_use_locales.include?(params[:disable_language])
            site.in_use_locales.delete(params[:disable_language])
            site.save
          end
        # Delete a language and the corresponding i18n_variables
        when 'delete'
          site = Site.find(session[:site])
          site.in_use_locales.delete(params[:delete_language])
          site.valid_locales.delete(params[:delete_language])
          site.save
          I18nVariable.destroy_all(:conditions => {:document_class => 'language', :key => params[:delete_language]})
      end
      redirect_to admin_translations_url
    rescue
      set_variables
      render :action => :edit
    end
  end
  
  protected
  
  # Get the i18n_variables and languages
  def set_variables
    @i18n_variables = I18nVariable.all.entries
    @language_i18n_variables =  @i18n_variables.inject([]) do |result, var|
      result << var if var.document_class.eql?('language')
      result
    end
    @role_i18n_variables =  @i18n_variables.inject([]) do |result, var|
      result << var if var.document_class.eql?('Role')
      result
    end
    @info_i18n_variables =  @i18n_variables.inject([]) do |result, var|
      result << var if var.document_class.eql?('UserInfoModel')
      result
    end
  end
  
end
