# -*- encoding : utf-8 -*-

class SurveySetsController < ApplicationController
  layout "survey"
  
  skip_before_filter :verify_authenticity_token
  
  
  def index
   
  end
  def new 
    @social_url = SurveyType::SOCIAL_URL
    @title = SurveyType::FACEBOOK_TITLE
    @description = SurveyType::DESCRIPTION
    @facebook_desc = SurveyType::FACEBOOK_DESC
    @twitter_desc = SurveyType::TWITTER_DESC
    
    
    if params[:survey_set_step]
      @survey_set_step = params[:survey_set_step].to_i
    else
      @survey_set_step = 1
    end
    
    
    @survey = SurveyType.find_by_slug(params[:slug])
    if session[:survey_set_id] and  @survey_set = SurveySet.find_by_id(session[:survey_set_id].to_i)
    
    else
    
      @survey_set = @survey.to_survey_set
    
    
      @survey_set.save
    
      session[:survey_set_id]= @survey_set.id
      
    end
    
    
    
  end
  
  def update
    @social_url = SurveyType::SOCIAL_URL
    @title = SurveyType::FACEBOOK_TITLE
    @description = SurveyType::DESCRIPTION
    @facebook_desc = SurveyType::FACEBOOK_DESC
    @twitter_desc = SurveyType::TWITTER_DESC
    
    if params[:survey_set_step]
      @survey_set_step = params[:survey_set_step].to_i
    else
      @survey_set_step = 1
    end
    
    @survey_set = SurveySet.find(params[:id])
    @survey_set.is_fill = true
    
    if session[:survey_set_id] = @survey_set.id
    

      if @survey_set_step == 4
      
        @survey_set.is_complete = true
      end
    
      if @survey_set.update_attributes(params.require(:survey_set).permit!)
        
        if @survey_set_step < 4
          
          
          
          redirect_to new_survey_set_path(:slug => @survey_set.survey_type.slug, :survey_set_step => (@survey_set_step+1))
        else
          
          session[:past_survey_set_id] = @survey_set.id
          session[:survey_set_id] = nil
          
          item = @survey_set.survey_type.items.find_by_slug("email")
          email = @survey_set.question_sets.find_by_survey_item_id(item.id).content.to_s
          if email != ""
            SurveyMails.thanks(@survey_set).deliver
          end
          
          
          redirect_to thank_survey_set_path(:slug => @survey_set.survey_type.slug, :id => @survey_set.id )
        end
      else
        render :action => :new
      end
      
      
    end
  end
  
  def thank
    @social_url = SurveyType::SOCIAL_URL
    @title = SurveyType::FACEBOOK_TITLE
    @description = SurveyType::DESCRIPTION
    @facebook_desc = SurveyType::FACEBOOK_DESC
    @twitter_desc = SurveyType::TWITTER_DESC
    
    
    @survey_set = SurveySet.find(params[:id])
     @survey_type = SurveyType.find_by_slug(params[:slug])

  end
end
