class MobileAppApi::V1::TaskController < MobileAppApi::V1::BaseController

  before_filter :login_required!

  def get_tasks
    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
    end_date = (start_date + 6.days).end_of_day.to_date
    group = @user.groups.find(params[:group_id]) if params[:group_id].present?
    tasks = @user.tasks.parent_tasks.where.not(id: @user.customized_tasks.select(:parent_id))
    tasks = tasks.for_group(group) if group
    tasks = tasks.includes(shares: :shared_to).non_responded_except_rejected(@user).for_date_range(start_date, end_date)
    tasks << @user.customized_tasks
    tasks = tasks.flatten.group_by {|t| t.start_time.to_date}
    render json: {status: 200, tasks: tasks, date_range: [start_date, end_date]}
  end

  def get_task
    begin
      task = @user.tasks.find(params[:id])
    rescue
      render json: {status: 401, error: 'Unauthorized'} and return
    end
    render json: {status: 200, task: serialized_task(task)}
  end

  def add_task
    task = @user.owned_tasks.build(task_params)
    if params[:course_id].present?
      group = Course.find(params[:course_id]).group
      task.group_id = group.id
      task.shares.build(user_id: @user.id, shared_to: group) unless params[:shares] == false
    end
    if !params[:user_emails].blank?
      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: @user.id, shared_to: user)
      end
    end
    task.confirmations.build(user: @user, state: 'accepted')
    if task.save
      Invite.invite_users(invitee_emails, task) if invitee_emails.present?
      render json: {status: 200, message: 'Task Added successfully.', task: serialized_task(task)}
    else
      render json: { status: 400, error: task.errors.full_messages }
    end
  end

  def update_task
    begin
      task = @user.tasks.find(params[:id])
      if task.update_attributes(task_params)
        if !params[:user_emails].blank?
          task.share_with!(params[:user_emails].split(','))
        end
        render json: {status: 200, message: 'Task updated successfully.', task: serialized_task(task)}
      else
        render json: { status: 400, error: task.errors.full_messages }
      end
    rescue
      render json: {status: 401, error: 'Unauthorized'} and return
    end
  end

  def remove_task
    begin
      task = @user.tasks.find(params[:id])
    rescue
      render json: {status: 401, error: 'Unauthorized'} and return
    end
    if task.can_delete?(@user)
      if task.destroy
        render json: {status: 200, message: 'Task removed successfully.'}
      else
        render json: {status: 500, error: 'Unable to remove task, kindly contact our support team.'}
      end
    else
      render json: {status: 401, error: 'Unauthorized'}
    end
  end

  def accept
    @task = @user.tasks.find(params[:id])
    @confirmation = @task.confirmations.build(user: @user)
    if @confirmation.accept and @confirmation.save
      TaskMailer.delay(queue: :mailer).notify_owner_for_task_acceptance(@task.id, @user.id, 'accepted') if @user.notification_enabled_for?('schedule')
    end
    begin
      notification = @user.notifications.find_by(trackable_id: @task)
      if notification.update_columns(response: "Accepted")
        render json: {status: 200, message: 'Task accepted successfully.'}
      else
        render json: {status: 500, error: 'Unable to accept task, kindly contact our support team.'}
      end
    rescue
      render json: {status: 401, error: 'Unauthorized'} and return
    end
  end

  def reject
    @task = @user.tasks.find(params[:id])
    @confirmation = @task.confirmations.build(user: @user)
    if @confirmation.reject and @confirmation.save
      TaskMailer.delay(queue: :mailer).notify_owner_for_task_acceptance(@task.id, @user.id, 'rejected') if @user.notification_enabled_for?('schedule')
    end
    begin
      notification = @user.notifications.find_by(trackable_id: @task)
      if notification.update_columns(response: "Rejected")
        render json: {status: 200, message: 'Task rejected successfully.'}
      else
        render json: {status: 500, error: 'Unable to reject task, kindly contact our support team.'}
      end
    rescue
      render json: {status: 401, error: 'Unauthorized'} and return
    end
  end

  private
  def task_params
    permitted_params = params.required(:task).permit(:name, :description, :stime, :date, :frequency, :schedule_type,
 :reminder, :group_id, :parent_id, :featured, :owner_id, shares_attributes: [:shared_to_id, :shared_to_type, :user_id, :id])
    permitted_params[:date] = Date.parse(permitted_params[:date]).try(:mm_dd_yyyy)
    permitted_params
  end

  def serialized_task(task)
    task.serializable_hash(only: [:id, :group_id, :name,
      :description, :start_time, :created_at, :updated_at, :frequency, :reminder, :status, :owner_id ],
      methods: [:editable])
  end

end
