import Foundation

// MARK: - Song File Writer

/// Writes a Song back to the text file format.
/// Shared between macOS and iOS targets.
struct SongFileWriter {
    static func write(song: Song) -> String {
        var lines: [String] = []

        // Title
        lines.append(song.title)

        // Metadata
        let keyAcc: String
        switch song.keySignature.accidental {
        case .sharp: keyAcc = "#"
        case .flat:  keyAcc = "b"
        default:     keyAcc = ""
        }
        lines.append("\(song.timeSignature), \(song.keySignature.tonic.rawValue)\(keyAcc) \(song.keySignature.mode.rawValue), \(song.defaultTempo) bpm")

        // Parts
        for part in song.parts {
            var tokens: [String] = [part.name]
            for note in part.notes {
                if note.isRest {
                    tokens.append("R")
                } else if let pitch = note.pitch {
                    tokens.append(pitch.description)
                }
                tokens.append(note.duration.description)
            }
            lines.append(tokens.joined(separator: " "))
        }

        return lines.joined(separator: "\n")
    }
}
