//
//  Overview.swift
//  Zockerhoehle
//
//  Created by Julian-Steffen Müller on 24.09.19.
//  Copyright © 2019 Julian-Steffen Müller. All rights reserved.
//

import SwiftUI
import CoreData

struct OverviewHeader<Destination : View> : View {
    private var destination : Destination
    private var title : String
    
    init(title : String, destination : Destination) {
        self.title = title
        self.destination = destination
    }
    
    var body : some View {
        HStack {
            Text("\(self.title)")
                .font(.headline)
                .padding(.leading, 15)
                .padding(.top, 5)
            Spacer()
            NavigationLink(destination: self.destination) {
                Text("Alle anzeigen")
                    .font(.caption)
                    .padding(.top, 10)
                    .padding(.trailing, 15)
            }
        }
    }
}

struct EmptyCategory : View {
    private var emptyMessage : String
    
    init(_ emptyMessage: String) {
        self.emptyMessage = emptyMessage
    }
    
    var body : some View {
        HStack() {
            Spacer()
            Text("Keine Spiele in der Zockerhöhle!").frame(height: 75)
            Spacer()
        }
    }
}

struct Overview: View {
    @Environment(\.managedObjectContext) private var viewContext
    
    @FetchRequest(entity: Game.entity(), sortDescriptors: [NSSortDescriptor(key: "createdAt", ascending: false), NSSortDescriptor(key: "name", ascending: true)])
    var games: FetchedResults<Game>
    
    @FetchRequest(entity: Console.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)])
    var consoles: FetchedResults<Console>
    
    @FetchRequest(entity: GameSeries.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)])
    var gameSeries: FetchedResults<GameSeries>

    let defaultImage = UIImage()
    
    let active_console_limt = 10;
    let last_picksups_limit = 10;
    
    var ConsolesOverview : some View {
        VStack(alignment: .leading) {
            OverviewHeader(title: "Aktivste Konsolen", destination: ConsolesListView())
            
            if consoles.count == 0 {
                EmptyCategory("Keine Konsolen in der Zockerhöhle!")
            }else{
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(alignment: .top, spacing: 0) {
                        ForEach(consoles.sorted(by: { Console.compareConsolesByNewestGame(consoleA: $0, consoleB: $1)}).prefix(active_console_limt)) { console in
                            NavigationLink(destination: ConsoleLibraryView(console: console)) {
                                VStack(alignment: .leading) {
                                        Group {
                                            Image(uiImage: ICloudManager.imageFrom(path: console.logo_icloud_path) ?? defaultImage)
                                                .resizable()
                                                .scaledToFit()
                                                .padding(10)
                                                .cornerRadius(5)
                                        }
                                        .frame(width: 100, height: 100)
                                    
                                    Text("\(console.name)")
                                        .font(.caption)
                                            .frame(width: 100)

                                    }.padding(.leading, 15)
                            }.buttonStyle(PlainButtonStyle())
                        }
                    }.padding(.trailing, 15)
                }
            }
        }
    }
    
    var GamesOverview : some View {
        VStack(alignment: .leading) {
            //TODO
            OverviewHeader(title: "Zuletzt gehortete Spiele", destination: GamePickupsView())
            
            if games.count == 0 {
                EmptyCategory("Keine Spiele in der Zockerhöhle")
            }else {
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(alignment: .top, spacing: 0) {
                        ForEach(games.prefix(last_picksups_limit)) { game in
                            NavigationLink(destination: GameDetailView(game: game)) {
                                VStack(alignment: .leading) {
                                        Group {
                                            Image(uiImage: ICloudManager.imageFrom(path: game.cover_icloud_path) ?? defaultImage)
                                                .resizable()
                                                .aspectRatio(contentMode: .fit)
                                                .cornerRadius(5)
                                        }
                                        .frame(width: 100, height: 100)
                                    
                                        Text("\(game.name)")
                                        .font(.caption)
                                            .frame(width: 100)

                                    }.padding(.leading, 15)
                            }.buttonStyle(PlainButtonStyle())
                        }
                    }.padding(.trailing, 15)
                }
            }
        }
    }
    
    var GameSeriesOverview : some View {
        VStack(alignment: .leading) {
            OverviewHeader(title: "Spielserien", destination: GameSeriesAllView())
            
            if gameSeries.count == 0 {
                EmptyCategory("Keine Spieleserie angelegt!")
            }else{
                ScrollView(.horizontal, showsIndicators: false) {
                    HStack(alignment: .top, spacing: 0) {
                        ForEach(gameSeries) { game_series in
                            NavigationLink(destination: GameSeriesLibraryView(gameSeries: game_series)) {
                                VStack(alignment: .leading) {
                                        Group {
                                            Image(uiImage: ICloudManager.imageFrom(path: game_series.cover_icloud_path) ?? defaultImage)
                                                .resizable()
                                                .scaledToFit()
                                                .cornerRadius(5)
                                        }
                                        .frame(width: 150, height: 150)
                                    
                                        Text("\(game_series.name ?? "n/a")")
                                        .font(.caption)
                                            .frame(width: 100)

                                    }.padding(.leading, 15)
                            }.buttonStyle(PlainButtonStyle())
                        }
                    }.padding(.trailing, 15)
                }
            }
        }
    }
    
    /*var featured : some View {
        VStack(alignment: .leading) {
            HStack {
                Text("Gerade Aktuell")
                    .font(.headline)
                    .padding(.leading, 15)
                    .padding(.top, 5)
                Spacer()
            }
            HStack {
                Spacer()
                if featuredStore.featuredConsole != nil {
                    NavigationLink(destination: ConsoleLibraryView(console: featuredStore.featuredConsole!)) {
                        if ICloudManager.fileExists(at: featuredStore.featuredConsole?.logo_icloud_path) {
                                Image(uiImage: ICloudManager.imageFrom(path: featuredStore.featuredConsole?.logo_icloud_path) ?? defaultImage)
                                    .resizable()
                                    .padding(10)
                                    .cornerRadius(5)
                        }else{
                            //TODO: Symbol für fehlendes Bild
                            Image(systemName: "cave").frame(width: 200, height: 200)
                        }
                    }.buttonStyle(PlainButtonStyle())
                }else {
                    EmptyCategory("Nichts aktuelles :(")
                }
                Spacer()
            }
            
        }
    }*/
    
    var body: some View {
        NavigationView {
            ScrollView(.vertical, showsIndicators: true) {
                VStack {
                    //featured
                    Text("TODO FEATURED")
                    Divider()
                    ConsolesOverview
                    Divider()
                    GamesOverview
                    Divider()
                    GameSeriesOverview
                }.navigationBarTitle("Zockerhöhle")
            }.navigationBarItems(trailing:
                NavigationLink(destination: SettingsView(), label: { Image(systemName: "gear") })
            ) 
        }.navigationViewStyle(StackNavigationViewStyle())
        
    }
}
