class TasksController < ApplicationController
  before_action :set_task, only: [:show, :edit, :update, :destroy]
  before_filter  :checkLoggedIn


  def checkLoggedIn
    authenticate_user!
  end

  # GET /tasks
  # GET /tasks.json
  def index
    if(params[:sort])
      @tasks = current_user.tasks.find(:all,:order=>params[:sort]+" "+if params[:direction]=="Descending" then "DESC" else "ASC"end)
    else
      @tasks=current_user.tasks.all
    end



    
  end

  # GET /tasks/1
  # GET /tasks/1.json
  def show
  end

  # GET /tasks/new
  def new
    @task = Task.new
  end

  # GET /tasks/1/edit
  def edit
  end

  # POST /tasks
  # POST /tasks.json
  def create
    @task = Task.new(task_params)
    @task.user_id=current_user.id
    respond_to do |format|
      if @task.save
        format.html { redirect_to @task, notice: 'Task was successfully created.' }
        format.json { render action: 'show', status: :created, location: @task }
      else
        format.html { render action: 'new' }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /tasks/1
  # PATCH/PUT /tasks/1.json
  def update
    respond_to do |format|
      if @task.update(task_params)
        format.html { redirect_to @task, notice: 'Task was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @task.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /tasks/1
  # DELETE /tasks/1.json
  def destroy
    @task.destroy
    respond_to do |format|
      format.html { redirect_to tasks_url }
      format.json { render json: @tasks}
    end
  end

  def changeCompleted
    @task_ids=params[:task_ids]
    #@task_ids=[]
    # Okay I have no idea why this caused a bit of a hassle
    #task_ids.each{|t| @task_ids.push(t[" "])}

    @tasks=current_user.tasks.find(@task_ids)

    if(params[:completion]=="Mark Complete")
      state=true

    elsif(params[:completion]=="Mark Incomplete")
      state=false
    end
@state=state
    @tasks.each{|t| 
        t.complete=state
        t.save!

        }
    
    respond_to do |format|
      format.html { redirect_to tasks_url }
      format.json { head :no_content }

    end
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_task
      @task = Task.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def task_params
      params.require(:task).permit(:name, :deadline, :complete,:sort)
    end
end
