# Copyright 2023 Google LLC
#
# Use of this source code is governed by an MIT-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/MIT.

require "io/console"
require_relative "../config/environment"
require_relative "models/singer"
require_relative "models/album"

class Application
  def self.run
    # Create a new singer.
    singer = create_new_singer

    # Create a new album.
    album = create_new_album singer

    # Verify that the album exists.
    find_album singer.singerid, album.albumid

    # List all singers, albums and tracks.
    list_singers_albums
  end

  def self.find_album singerid, albumid
    album = Album.find [singerid, albumid]
    puts "Found album: #{album.title}"
  end

  def self.list_singers_albums
    puts ""
    puts "Listing all singers with corresponding albums"
    Singer.all.order("last_name, first_name").each do |singer|
      puts "#{singer.first_name} #{singer.last_name} has #{singer.albums.count} albums:"
      singer.albums.order("title").each do |album|
        puts "  #{album.title}"
      end
    end
  end

  def self.create_new_singer
    # Create a new singer. The singerid is generated by the bit-reversed sequence in the database and returned.
    puts ""
    singer = Singer.create first_name: "Melissa", last_name: "Garcia"
    puts "Created a new singer '#{singer.first_name} #{singer.last_name}' with id #{singer.singerid}"

    singer
  end

  def self.create_new_album singer
    # Create a new album.
    puts ""
    puts "Creating a new album for #{singer.first_name} #{singer.last_name}"
    # The albumid is not generated by a sequence in the database.
    album = singer.albums.build albumid: 1, title: "New Title"
    album.save!

    album
  end
end

Application.run
