class TasksController < ApplicationController
  before_filter :require_login, except: [:accept, :reject, :accept_changes, :reject_changes]
  before_filter :find_task, except: [:new, :create, :index, :accept, :reject, :edit]
  skip_before_filter :check_for_previous_confirmed_sessions

  def index
    @start_date = if params[:start_date]
      Date.parse(params[:start_date])
    else
      Date.today_in_time_zone.beginning_of_day.to_date - 1.day
    end
    if params[:group_id].blank?
      @task = Task.new(reminder: 2)
    else
      @group = current_user.groups.find(params[:group_id])
      #@task = @group.tasks.build(reminder: 2)
      @task = current_user.owned_tasks.build(reminder: 2)
    end
    @end_date = (@start_date + 6.days).end_of_day.to_date
    find_tasks
  end

  def show
    redirect_to tasks_path(start_date: @task.start_time.beginning_of_day)
  end

  def edit
    @task = Task.find(params[:id])
    if !@task.can_delete?(current_user)
      new_task = @task.dup
      new_task.parent_id = @task.id
      @task = new_task
    end
    render layout: false
  end

  def update
    if @task.update_attributes(task_params)
      if !params[:user_emails].blank?
        @task.share_with!(params[:user_emails].split(','))
      end
      respond_to do |format|
        message = 'Task updated successfully.'
        format.html {redirect_to params[:type].present? ? tasks_path(type: param[:type]) : tasks_path, notice: message}
        format.js {redirect_via_turbolinks_to params[:type].present? ? tasks_path(type: params[:type]) : tasks_path, notice: message}
      end
    else
      respond_to do |format|
        format.js {render 'save'}
        format.json {render json: {error: @task.errors.full_messages}, status: 403}
      end
    end
  end

  def new
    @task = Task.new(reminder: 2)
    render layout: false
  end

  def create
    @task = current_user.owned_tasks.build(task_params)
    if params[:task][:group_id].present?
      group = current_user.groups.find(params[:task][:group_id])
      @task.shares.build(user_id: current_user.id, shared_to: group)
    end
    if params[:user_emails].present?
      users = User.where(email: params[:user_emails].split(','))
      @invitee_emails = params[:user_emails].split(',') - users.map(&:email)
      users.each do |user|
        @task.shares.build(user_id: current_user.id, shared_to: user)
      end
    end
    @task.confirmations.build(user: current_user, state: 'accepted')
    if @task.save
      Invite.invite_users(@invitee_emails, @task) if @invitee_emails.present?
      respond_to do |format|
        message = 'Task added successfully.'
        format.html {redirect_to params[:type].present? ? tasks_path(type: param[:type]) : tasks_path, notice: message}
        format.js {redirect_via_turbolinks_to params[:type].present? ? tasks_path(type: params[:type]) : tasks_path, notice: message}
      end
    else
      respond_to do |format|
        format.js {render partial: 'inline_form', replace: 'form#new_task'}
      end
    end
  end

  def destroy
    if @task.can_delete?(current_user)
      @destroyed = @task.destroy
    else
      @task.group_schedule_exceptions.find_or_create_by(user: current_user)
      @destroyed = true
    end
    respond_to do |format|
      format.js {render 'remove'}
    end
  end

  def delete_parent
    @task.group_schedule_exceptions.find_or_create_by(user: current_user)
    @destroyed = true
    respond_to do |format|
      format.js {render 'remove'}
    end
  end

  def accept
    @task = current_user.tasks.find(params[:id])
    @confirmation = @task.confirmations.build(user: current_user)
    if @confirmation.accept and @confirmation.save
      TaskMailer.delay(queue: :mailer).notify_owner_for_task_acceptance(@task.id, current_user.id, 'accepted') if current_user.notification_enabled_for?('schedule')
    end
    notification = current_user.notifications.find_by(trackable_id: @task)
    notification.update_columns(response: "Accepted") if notification
    respond_to do |format|
      format.js {render 'confirmation'}
      format.html{redirect_to task_path(@task.id)}
    end
  end

  def reject
    @task = current_user.tasks.find(params[:id])
    @confirmation = @task.confirmations.build(user: current_user, accepted: false)
    if @confirmation.reject and @confirmation.save
      TaskMailer.delay(queue: :mailer).notify_owner_for_task_acceptance(@task.id, current_user.id, 'rejected') if current_user.notification_enabled_for?('schedule')
    end
    notification = current_user.notifications.find_by(trackable_id: @task)
    notification.update_columns(response: "Rejected") if notification
    respond_to do |format|
      format.js {render 'confirmation'}
      format.html {redirect_to task_path(@task.id)}
    end
  end

  def toggle_completion
    date = params[:selected_date]
    if @task.completed_by?(current_user, date)
      @task.mark_uncompleted!(current_user, date)
    else
      @task.mark_completed!(current_user, date)
    end
    respond_to do |format|
      format.js
    end
  end

  def accept_changes
    @new_task = @task.create_copy_for(current_user)
    if @new_task.save validate: false
      @confirmation = @task.update_confirmations.build(user_id: current_user.id, accepted: true)
      @confirmation.save validate: false
    end
    notification = current_user.notifications.find_by(trackable_id: @task)
    notification.update_columns(response: "Accepted") if notification
    respond_to do |format|
      format.js {render 'confirmation'}
    end
  end

  def reject_changes
    @confirmation = @task.update_confirmations.build(user_id: current_user.id, accepted: false)
    @confirmation.save
    notification = current_user.notifications.find_by(trackable_id: @task)
    notification.update_columns(response: "Rejected") if notification
    respond_to do |format|
      format.js {render 'confirmation'}
    end
  end

  private
  def task_params
    params.required(:task).permit(:name, :description, :stime, :date, :frequency, :schedule_type,
 :reminder, :group_id, :parent_id, :featured, :owner_id)
  end

  def find_task
    @task = current_user.tasks.find(params[:id])
  end

  def find_tasks
    @tasks = current_user.tasks.parent_tasks.where.not(id: current_user.customized_tasks.select(:parent_id)).except_rejected_by(current_user).responded_by_user(current_user)
    @tasks = @tasks.for_group(@group) if @group
    @tasks = @tasks.includes(shares: :shared_to).for_date_range(@start_date, @end_date)
    @tasks << current_user.customized_tasks#.where(parent_id: @tasks)
    @tasks = @tasks.flatten.group_by {|t| t.start_time.to_date}
  end
end
