class SubDomainsController < ApplicationController
  layout 'base_org'
  before_filter :find_org_subfield_and_subdomain, :only => [:show, :index, :domain_update_priority, :destroy, :update, :hide_sub_domain, :show_sub_domain]

  def new
    @subdomain = SubDomain.new
    @org_subfield = OrgSubfield.find(params[:org_subfield_id])
    @organization = @org_subfield.organization
  end

  def create
    if SubDomain.where("org_subfield_id=#{params[:org_subfield_id]} and name=?",params[:name]).count == 0
      @res = true
      @subfield = OrgSubfield.find(params[:org_subfield_id])
      @organization = @subfield.organization
      @subdomain = SubDomain.create(:name => params[:name], :org_subfield_id => params[:org_subfield_id], :priority => @subfield.sub_domains.blank? ? 1 : @subfield.sub_domains.order("priority").last.priority + 1)
      @subdomain.update_column(:field_type, params[:field_type])
    else
      @res = false
    end
  end

  def update
    @subdomain.update_column(:name, params[:name])
  end

  def domain_update_priority
    @subdomain.update_attribute(:priority, params[:priority].to_i)
  end

  def destroy
    @subdomain.destroy
  end

  def show
    render_404
    # @subfield_content = @organization.org_subfields.order("priority")
    # render layout: @organization.switch_type ? 'base_sub_domain' : 'base_org'
  end

  def index

  end

  def hide_sub_domain
    @subdomain.update_attribute(:hide, 1)
  end

  def show_sub_domain
    @subdomain.update_attribute(:hide, 0)
  end


  private
  def find_org_subfield_and_subdomain
    @subfield = OrgSubfield.find(params[:org_subfield_id])
    @subdomain = SubDomain.find(params[:id])
    @organization = @subfield.organization
  rescue ActiveRecord::RecordNotFound
    # source_subdomain not found
    render_404
  end
end
