class Admin::ItemsController < OrbitBackendController
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::DynamicForm

  layout "structure"

  open_for_admin
  
  def index
    if params[:item_id]
      @item = Item.find(params[:item_id])
    else
      @item = get_homepage
    end
  end

  def destroy
    @item = Item.find(params[:id])
    @item.destroy
    respond_to do |format|
      format.js  { render 'admin/items/reload_items' }
    end
  end

  def update_position
    item = Item.find(params[:id])
    item.shift_to(params[:parent_id], params[:position].to_i, params[:next_sibling_id])
    render :nothing => true, status: 200
  end

  def get_page_design_module_json
    designs = Design.all.inject([]) do |designs, design|
      d = {}
      d["main"] = [design.title, design.id.to_s, (design.site.present? ? 1 : 0)]
      d["sub"] = design.themes.map{|theme| [theme.name, theme.id.to_s]} rescue ''
      designs << d
    end
    modules = ModuleApp.for_frontend_select.inject([]) do |module_apps, module_app|
      m = {}
      m["main"] = [module_app.label, module_app.id.to_s]
      m["sub"] = module_app.app_pages.map{|name, data| [t(data["i18n"]), name]} rescue []
      m["sub"] << [I18n.t('default_widget.default_widget'),'default_widget'] if module_app.has_default_widget?
   
      if module_app.key == 'member'
        m["category"] = RoleStatus.where(:role_id=> RoleStatus.get_role_data("teacher") ).map{|category| [category.title, category.id.to_s] } rescue ''
        m["tags"] = RoleCategory.where(:role_id=> RoleCategory.get_role_data("teacher") ).map{|category| [category.title, category.id.to_s] } rescue ''
      elsif module_app.key == 'member_staff'
        m["category"] = RoleStatus.where(:role_id=> RoleStatus.get_role_data("staff") ).map{|category| [category.title, category.id.to_s] } rescue ''
        m["tags"] = RoleCategory.where(:role_id=> RoleCategory.get_role_data("staff") ).map{|category| [category.title, category.id.to_s] } rescue ''
      else
        m["category"] = module_app.categories.map{|category| [category.title, category.id.to_s] } rescue ''
        m["tags"] = module_app.tags.map{|tag| [tag.name, tag.id.to_s] } rescue ''
      end

      m["count"] = module_app.get_registration.get_data_count.to_a
      module_apps << m
    end
    render json: JSON.pretty_generate({design: designs, module: modules})
  end
  
end
