When(/^I am on the Manage CMS Accounts page/) do
  if !on(OA::BasePage).page_title? || on(OA::BasePage).page_title != "Manage CMS Accounts"
    visit OA::RelationshipsPage
    on(OA::RelationshipsPage).manage_cms_accounts_link
  end
  expect(on(OA::ManageCmsAccounts).page_title_element.when_present.text).to eql("Manage CMS Accounts")
end

Then(/^I edit a CMSA$/) do
  on OA::ManageCmsAccounts do |page|
    new_cmsa_name = "A Watir Tester"
    page.look_for_editable_cmsa(new_cmsa_name)
    page.cms_accounts_table_element[new_cmsa_name]["Edit"].link_element.click
    page.edit_cmsa_content_owner = "WatirContentOwner"
    page.edit_cmsa_display_name = new_cmsa_name
    page.edit_cmsa_notes = "Last edited on #{@edit_time = Time.new.strftime('%Y-%m-%d %H:%M:%S')}"
    page.submit_button
    page.look_for_editable_cmsa new_cmsa_name
    updated_notes = page.cms_accounts_table_element[new_cmsa_name]["Notes"].text
    puts "Updated notes for A Watir Tester: #{updated_notes}"
  end
end

And(/^the CMSA's timestamp should be updated$/) do
  on OA::ManageCmsAccounts do |page|
    expect(page.cms_accounts_table_element["A Watir Tester"]["Notes"].text).to include(@edit_time)
  end
end

Then(/^I create a CMSA$/) do
  on OA::ManageCmsAccounts do |page|
    page.add_cms_account_link
    creation_time = Time.new.strftime("%Y-%m-%d %H:%M:%S")
    @new_watir_owner = "WatirOwner#{creation_time}"
    @new_watir_cmsa = "A Watir CMSA #{creation_time}"
    page.edit_cmsa_content_owner = @new_watir_owner
    page.edit_cmsa_display_name = @new_watir_cmsa
    page.edit_cmsa_notes = "Woot \nWooot \nWoooot \nWooooot \nGian \ntotally \nrules"
    page.submit_button
  end
end

And(/^the CMSA should exist$/) do
  on OA::ManageCmsAccounts do |page|
    fail "The new CMSA is not in the table" unless
      page.cms_accounts_table_element.any? { |row| row["CMSA Display name"].text == @new_watir_cmsa }
  end
end

Then(/^I delete test CMSAs$/) do
  on OA::ManageCmsAccounts do |page|
    while page.cmsa_in_table? "A Watir CMSA"
      cmsa_to_delete = page.cms_accounts_table_element["A Watir CMSA"]["CMSA Display name"].text
      page.cms_accounts_table_element["A Watir CMSA"]["Edit"].link_element.click
      page.delete_link
      expect(page.cms_accounts_table_element["A Watir"]["CMSA Display name"].text).to_not eq(cmsa_to_delete)
      puts "Deleted CMSA: #{cmsa_to_delete}"
    end
  end
  puts "There are no test CMSAs to delete"
end
