class TaskListsController < ApplicationController
  before_action :set_task_list, only: [:show, :edit, :update]
  before_action :make_temporary_tasks_expire, only: [:show]

  def new
    @latest_five_task_lists = latest_five_task_lists
    @task_list = TaskList.new
  end

  def show
    @next_new_task = Task.new
    @next_new_task.task_list = @task_list
  end

  def create
    @task_list = TaskList.new(task_list_params)

    respond_to do |format|
      if @task_list.save
        add_to_latest_five(@task_list)
        format.html { redirect_to @task_list, notice: 'Task List was successfully created.' }
      else
        @latest_five_task_lists = latest_five_task_lists
      	format.html { render :new }
      end
    end
  end

  def update
    respond_to do |format|
      if @task_list.update(task_list_params)
        format.json { render 'update_success' }
      else
        format.json { render 'update_error' }
      end
    end
  end

  private

    # Use callbacks to share common setup or constraints between actions.
    def set_task_list
      @task_list = TaskList.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def task_list_params
      params.require(:task_list).permit(:title)
    end

    def latest_five_task_lists
      session[:latest_five] ||= []
      session[:latest_five].map { |url| TaskList.find(url) }.reject { |task_list| task_list.nil? }
    end

    def add_to_latest_five(task_list)
      session[:latest_five] ||= []
      session[:latest_five].shift unless session[:latest_five].size < 5
      session[:latest_five] << task_list.url
    end
   
    # For each temporary task in the list, it sets its status to 4: EXPIRED if temporary task's end_date is older than current date.
    def make_temporary_tasks_expire
      @task_list.temporary_tasks.each do |temporary_task|
        if temporary_task.status != 4 && temporary_task.due_date_passed?
          temporary_task.update_attribute(:status, 4) 
        end
      end
    end
end
