def add_rehearsal_song(rehearsal_id, song_id, pos):
    try:
        rehearsal = get_rehearsal(rehearsal_id)
        song = get_song(song_id)

        if rehearsal.setlist.contains(song):
            raise Exception("This song is already on the setlist!")

        aSong = AllocatedSong(setlist=rehearsal.setlist, song=song, position=pos)
        aSong.save()

        # advances each song in the setlist after my new position by 1 position
        if (rehearsal.setlist.count > 0):
            for aSong in AllocatedSong.objects.filter(setlist=rehearsal.setlist, position__gte=pos).exclude(song=song):
                aSong.position += 1
                aSong.save()

        return rehearsal
    except Exception as exc:
        raise Exception("Error adding song to rehearsal's setlist: %s" % exc.message)
def add_gig_song(gig_id, song_id, pos):
    try:
        gig = get_gig(gig_id)
        song = get_song(song_id)

        if gig.setlist.contains(song):
            raise Exception("This song is already on the setlist!")

        newSong = AllocatedSong(setlist=gig.setlist, song=song, position = pos)
        newSong.save()
        
        # advances each song in the setlist after my new position by 1 position
        if (gig.setlist.count > 0):
            for aSong in AllocatedSong.objects.filter(setlist=gig.setlist, position__gte=pos).exclude(song=song):
                aSong.position += 1
                aSong.save()
                
        return gig
    except Exception as exc:
        raise Exception("Error adding song to gig's setlist: %s" % exc.message)
def add_setlist_song(band_id, artist, title):
    try:
        band = get_band(band_id)

        song = Song.objects.filter(band = band, artist = artist, title = title)
        if len(song) == 0:
            song = Song.objects.create(band = band, artist = artist, title = title)
        else:
            song = song[0]

        if band.setlist.contains(song):
            raise SongAlreadyOnSetlistError(song, "This song is already on the setlist!")

        aSong = AllocatedSong(setlist=band.setlist, song=song)
        aSong.save()

        return band
    except SongAlreadyOnSetlistError:
        raise
    except Exception as exc:
        raise Exception("Error adding song: %s" % exc.message)