class Panel::SurveyB::FrontEnd::SurveyBController < OrbitWidgetController
  helper ApplicationHelper

  def index
    if params[:period].nil?
      @period = SurveyBPeriod.get_current_survey()
    else
      @period = SurveyBPeriod.find(params[:period])
    end
    
    redirect_standalone panel_survey_b_front_end_survey_b_index_path( :standalone => 'true') do
      @setting = SurveyBSetting.first_or_create
      if params[:agree] == '1'
        # @period = SurveyBPeriod.first
        render :index, :layout => 'standalone'
      else
        # Escape from error when announcement is empty
        if @setting.announcement.nil?
          @setting.announcement = " "
        end
        render :announcement, :layout => 'standalone'
      end
    end
  end

  def create
    answer = params[:answer]
    @answer_model = ::SurveyBAnswer.new
    not_answered = true
    [:contact_name, :contact_phone, :contact_e_mail, :person_question, :rate_question, :quality_question].each do |item|
      if answer[item].blank?
        @answer_model.errors.add t("survey_b.#{item.to_s}_label"), t('survey_b.not_answered')
      else
        @answer_model[item] = answer[item]
      end
    end
    @answer_model[:comment_question] = answer[:comment_question]
    [:good_institutions, :bad_institutions].each do |item|
      t('survey_b.institutions').each do |i_key, institution|
        if answer[item][i_key] == '1'
          @answer_model[item] ||= []
          @answer_model[item].push i_key
        end
      end
    end
    t('survey_b.institutions').each do |i_key, institution|
      if answer["institution_check"][i_key] == '1'
        not_answered = false
        @answer_model[i_key] ||= {}
        t('survey_b.questions').each do |q_key, question|
          if answer[i_key] && answer[i_key][q_key]
            @answer_model[i_key][q_key] = answer[i_key][q_key]
          else
            @answer_model.errors.add institution + question, t('survey_b.not_answered')
          end
        end
      end
    end
    if not_answered
      @answer_model.errors.add t('survey_b.institution_check_label'), t('survey_b.not_answered')
    end
    if @answer_model.errors.empty?
      @answer_model.save!
      render :answer_success
    else
      @answer_error = @answer_model.errors.full_messages.join(',')
      render :answer_error
    end
  end

  def redirect_standalone url
    unless params[:standalone] == 'true'
      @redirect_url = url
      render :redirect_standalone
    else
      module_app = ModuleApp.first(:conditions => {:key => 'survey_b'})
      @item = Item.where(module_app_id: module_app.id).first
      
      if @period
        yield
      else
        # render :no_survey
        # render :json => "No Survey"
        render :no_survey, :layout => 'standalone'
      end
    end
  end
end