require 'csv'

class Panel::Ask::BackEnd::AskQuestionsController < OrbitBackendController

  def initialize
    super
    @app_title = 'ask_questions'
  end

  def index
    @ask_questions = AskQuestion.all
    
    respond_to do |format|
      format.html
      format.js
    end
  end

  def edit
    @ask_question = AskQuestion.find(params[:id])
    @ask_reply = @ask_question.ask_reply
    if @ask_reply
      @url = panel_ask_back_end_ask_question_ask_reply_path(@ask_question, @ask_question.ask_reply)
      @method = 'put'
    else
      @ask_reply = AskReply.new
      @url = panel_ask_back_end_ask_question_ask_replies_path(@ask_question)
      @method = 'post'
    end
  end

  def destroy
    @ask_question = AskQuestion.find(params[:id])
    @ask_question.destroy

    respond_to do |format|
      format.js
    end
  end

  def delete
    if params[:ids]
      ask_questions = AskQuestion.any_in(:_id => params[:ids]).destroy_all
    end
    redirect_to panel_ask_back_end_ask_questions_url(:direction => params[:direction], :sort => params[:sort], :sort_options => params[:sort_options])
  end

  def export

  end

  def do_export
    Rails.application.config.mongoid.use_activesupport_time_zone = true
    date_start = "#{params[:export]['start(1i)']}-#{params[:export]['start(2i)']}-#{params[:export]['start(3i)']}"
    date_end = "#{params[:export]['end(1i)']}-#{params[:export]['end(2i)']}-#{params[:export]['end(3i)']}"
    @ask_questions = AskQuestion.includes(:ask_category).includes(:ask_reply).where(:created_at.gte => date_start, :created_at.lte => date_end)

    csv = CSV.generate do |csv|
      csv << [ t('category'),
               AskQuestion.human_attribute_name(:name),
               AskQuestion.human_attribute_name(:identity),
               AskQuestion.human_attribute_name(:email),
               AskQuestion.human_attribute_name(:phone),
               AskQuestion.human_attribute_name(:tax),
               AskQuestion.human_attribute_name(:title),
               AskQuestion.human_attribute_name(:content),
               AskReply.human_attribute_name(:content),
               AskReply.human_attribute_name(:comment)]
      @ask_questions.each do |ask_question|
        ask_question.ask_reply ||= AskReply.new
        csv << [ ask_question.ask_category.name,
                 ask_question.name,
                 ask_question.identity,
                 ask_question.email,
                 ask_question.phone,
                 ask_question.tax,
                 ask_question.title,
                 ask_question.content,
                 ask_question.ask_reply.content,
                 ask_question.ask_reply.comment ]
      end
    end
    send_data csv.encode('Big5'), type: 'text/csv',  filename: "Questions-#{date_start}-#{date_end}.csv"
  end
end
