def successful_lesson(lesson_session, advance_to_end = true)
  # teacher & student get into session
  start = lesson_session.scheduled_start
  end_time = lesson_session.scheduled_start + (60 * lesson_session.duration)
  uh2 = FactoryGirl.create(:music_session_user_history, user: lesson_session.teacher, history: lesson_session.music_session, created_at: start, session_removed_at: end_time)
  uh2 = FactoryGirl.create(:music_session_user_history, user: lesson_session.student, history: lesson_session.music_session, created_at: start, session_removed_at: end_time)
  # artificially end the session, which is covered by other background jobs
  lesson_session.music_session.session_removed_at = end_time
  lesson_session.music_session.save!

  if advance_to_end
    Timecop.travel(end_time + 60 * 60)
  end
end

def failed_lesson(lesson_session, advance_to_end = true)
  start = lesson_session.scheduled_start
  end_time = lesson_session.scheduled_start + (60 * lesson_session.duration)
  if advance_to_end
    Timecop.travel(end_time + 60 * 60)
  end
end
def teacher_approve(lesson_session)

  #sign_out_poltergeist(validate: true)
  sign_out
  sign_in_poltergeist(lesson_session.teacher, password: 'foobar')
  visit "/client#/jamclass/lesson-booking/" + lesson_session.id
  find(".slot-decision-field[data-slot-id=\"#{lesson_session.lesson_booking.default_slot.id}\"] ins", visible: false).trigger(:click)
  find('.schedule.button-orange').trigger(:click)
  # dismiss banner
  #find('a.button-orange', text:'CLOSE').trigger(:click)
  find('tr[data-lesson-session-id="' + lesson_session.id + '"] .displayStatusColumn', text: 'Scheduled')
end

def date_picker_format(date)
  date.strftime('%a %b %d %Y')
end
def fill_out_single_lesson(first_date = Date.new(2016, 4, 17), second_date = Date.new(2016, 4, 18))

  first = first_date.strftime('%a %d %b %Y')
  second = second_date.strftime('%a %d %b %Y')

  find('h2', text: 'book testdrive lesson')
  find('.booking-info', text: 'If you need to cancel')

  # book the lesson
  fill_in "slot-1-date", with: first# "Sun Apr 17 2016"
  #find('.slot.slot-1 input.hasDatepicker').trigger(:click)
  # click 4-6
  find('td a', text: first_date.day).trigger(:click)

  #find('.slot.slot-2 input.hasDatepicker').trigger(:click)
  # click 4-7
  fill_in "slot-2-date", with: second #"Mon Apr 18 2016"
  find('td a', text: second_date.day).trigger(:click)

  fill_in 'user-description', with: 'abc def dog neck'

  sleep 3


  find('a.book-lesson-btn', text: 'BOOK TESTDRIVE LESSON').trigger(:click)

end

def validate_status(lesson, expectedStatus)
  find('tr[data-lesson-session-id="' + lesson.id + '"] td.displayStatusColumn', text: expectedStatus)
end


def jamclass_hover_option(lesson, option, text)
  # open up hover
  find('tr[data-lesson-session-id="' + lesson.id + '"] .lesson-session-actions-btn').trigger(:click)
  find('li[data-lesson-option="' + option + '"] a', visible: false, text: text).trigger(:click)
end

def counter_day(lesson)
  fill_in "alt-date-input", with:  date_picker_format(Date.new(Date.today.year, Date.today.month + 1, 17))
  find('td a', text: '17').trigger(:click)
  sleep 3
  find('.schedule.button-orange').trigger(:click)
  find('#banner h1', text: 'Lesson Change Requested')
  find('#banner .close-btn').trigger(:click)
  find('tr[data-lesson-session-id="' + lesson.id + '"] td.displayStatusColumn', text: 'Requested')
end

def approve_lesson(lesson, slot = lesson.lesson_booking.default_slot)
  find(".slot-decision-field[data-slot-id=\"#{slot.id}\"] ins", visible: false).trigger(:click)
  find('.schedule.button-orange').trigger(:click)
  find('tr[data-lesson-session-id="' + lesson.id + '"] td.displayStatusColumn', text: 'Scheduled')
end

def fill_out_payment(expected = nil, name = nil )

  if name
    fill_in 'name', with: name
  end
  fill_in 'card-number', with: '4111111111111111'
  fill_in 'expiration', with: '11/2016'
  fill_in 'cvv', with: '111'
  fill_in 'zip', with: '78759'

  if expected
    find('.booking-info', text: expected)
  end
  find('.purchase-btn').trigger(:click)

  # it needs to go 'disabled state' to indicate it's updating
  find('.purchase-btn.disabled')
end

def select_test_drive(count = 4)
  find(".button-orange.select-#{count}").trigger(:click)
end

def create_stripe_token(exp_month = 2019)
  Stripe::Token.create(
      :card => {
          :number => "4111111111111111",
          :exp_month => 2,
          :exp_year => exp_month,
          :cvc => "314"
      },
  ).id
end



def book_lesson(user, teacher, options)

  if options[:package_count].nil?
    options[:package_count] = 4
  end

  if options[:slots].nil?
    slots = []
    if options[:monthly]
      slots << FactoryGirl.build(:lesson_booking_slot_recurring)
      slots << FactoryGirl.build(:lesson_booking_slot_recurring)
    else
      slots << FactoryGirl.build(:lesson_booking_slot_single)
      slots << FactoryGirl.build(:lesson_booking_slot_single)
    end

  else
    slots = options[:slots]
  end

  if user.stored_credit_card == false
    token = create_stripe_token
    result = user.payment_update({token: token, zip: '78759', normal: true})
    #user.stored_credit_card = true
    #user.save!
  end

  if options[:test_drive]
    booking = LessonBooking.book_test_drive(user, teacher, slots, "Hey I've heard of you before.")
  elsif options[:normal]
    booking = LessonBooking.book_normal(user, teacher, slots, "Hey I've heard of you before.", false, LessonBooking::PAYMENT_STYLE_SINGLE, 60)
  elsif options[:monthly]
    booking = LessonBooking.book_normal(user, teacher, slots, "Hey I've heard of you before.", true, LessonBooking::PAYMENT_STYLE_MONTHLY, 60)
  end
  if booking.errors.any?
    puts "BOOKING #{booking.errors.inspect}"

    if booking.lesson_booking_slots[0].errors.any?
      puts "SLOT0 #{booking.lesson_booking_slots[0].errors.inspect}"
    end
  end


  booking.errors.any?.should be false unless options[:no_validate]

  lesson = booking.lesson_sessions[0]
  start = lesson.scheduled_start
  end_time = lesson.scheduled_start + (60 * lesson.duration)

  booking.card_presumed_ok.should be true unless options[:no_validate]

  if options[:test_drive]
    if user.most_recent_test_drive_purchase.nil?
      LessonPackagePurchase.create(user, booking, LessonPackageType.package_for_test_drive_count(options[:package_count]))
    end
  end

  if options[:counter]
    if options[:monthly]
      counter_slot = FactoryGirl.build(:lesson_booking_slot_recurring)
    else
      counter_slot = FactoryGirl.build(:lesson_booking_slot_single)
    end

    lesson.counter({proposer: user, message: "countered YEAH!", slot: counter_slot})
    lesson.reload
    lesson.status.should eql LessonSession::STATUS_COUNTERED
  end

  if options[:accept]
    lesson.accept({message: 'Yeah I got this', slot: slots[0].id, accepter: teacher})
    lesson.errors.any?.should be false unless options[:no_validate]
    lesson.reload
    lesson.slot.should eql slots[0] unless options[:no_validate]
    lesson.status.should eql LessonSession::STATUS_APPROVED unless options[:no_validate]
  end

  if options[:cancel]
    lesson.cancel({canceler: options[:canceler] || user, message: "sorry about that"})
    lesson.reload
    lesson.status.should eql LessonSession::STATUS_CANCELED unless options[:no_validate]
  end

  if options[:miss]
    # teacher & student get into session

    Timecop.travel(end_time + 1)
    lesson.analyse
    lesson.session_completed
  elsif options[:teacher_miss]
    uh2 = FactoryGirl.create(:music_session_user_history, user: user, history: lesson.music_session, created_at: start, session_removed_at: end_time)
    # artificially end the session, which is covered by other background jobs
    lesson.music_session.session_removed_at = end_time
    lesson.music_session.save!
    Timecop.travel(end_time + 1)
    lesson.analyse
    lesson.session_completed
  elsif options[:success]
    uh1 = FactoryGirl.create(:music_session_user_history, user: user, history: lesson.music_session, created_at: start, session_removed_at: end_time)
    uh2 = FactoryGirl.create(:music_session_user_history, user: teacher, history: lesson.music_session, created_at: start, session_removed_at: end_time)
    # artificially end the session, which is covered by other background jobs
    lesson.music_session.session_removed_at = end_time
    lesson.music_session.save!
    Timecop.travel(end_time + 1)
    lesson.analyse
    lesson.session_completed
  elsif options[:finish]
    # teacher & student get into session
    uh2 = FactoryGirl.create(:music_session_user_history, user: teacher, history: lesson.music_session, created_at: start, session_removed_at: end_time)
    if options[:student_show]
      uh2 = FactoryGirl.create(:music_session_user_history, user: user, history: lesson.music_session, created_at: start, session_removed_at: end_time)
    end
    # artificially end the session, which is covered by other background jobs
    lesson.music_session.session_removed_at = end_time
    lesson.music_session.save!

    Timecop.travel(end_time + 1)


    lesson.analyse
    lesson.session_completed

    if options[:monthly]
      LessonBooking.hourly_check
    end
  end

  lesson
end

def testdrive_lesson(user, teacher, options = {finish: false, accept: true, cancel: false, miss: false, slots: nil})
  options[:test_drive] = true
  book_lesson(user, teacher, options)
end


def normal_lesson(user, teacher, options = {finish: false, accept: true, cancel: false, miss: false, slots: nil})
  options[:normal] = true
  book_lesson(user, teacher, options)
end


def monthly_lesson(user, teacher, options = {finish: false, accept: true, cancel: false, miss: false, slots: nil})
  options[:monthly] = true
  book_lesson(user, teacher, options)
end