/**
 *  https://gist.github.com/tadija/cb4ec0cbf0a89886d488d1d8b595d0e9
 *  Copyright (c) Marko Tadić 2018
 *  Licensed under the MIT license. See LICENSE file.
 */

import SwiftUI

struct ToggleFonts: View {

    @State private var textSample: String?
    @State private var fontSize: CGFloat

    @State private var fontIndex: Int = 0 {
        didSet {
            print("(\(fontIndex)/\(allFonts.count): \(fontNames[fontIndex])")
        }
    }

    init(
        textSample: String? = nil,
        fontSize: CGFloat = 24
    ) {
        self.textSample = textSample
        self.fontSize = fontSize
    }

    var body: some View {
        Text(textSample ?? fontNames[fontIndex])
            .font(allFonts[fontIndex])
            .onTapGesture {
                nextFont()
            }
            .onLongPressGesture {
                previousFont()
            }
    }

    func nextFont() {
        guard fontIndex < allFonts.count - 1 else {
            fontIndex = 0; return
        }
        fontIndex += 1
    }

    func previousFont() {
        guard fontIndex > 0 else {
            fontIndex = allFonts.count - 1; return
        }
        fontIndex -= 1
    }

    var allFonts: [Font] {
        fontNames.map {
            .custom($0, size: fontSize)
        }
    }

    let fontNames = UIFont.allFontNames()
}