//
//  SearchContainer.swift
//  Comedores Sociales
//
//  Created by Hector Carrion on 11/30/20.
//

import SwiftUI

struct SearchContainer: View {
    @State var filteredItems = foods
    @State var showingProfile: Bool = false
    @EnvironmentObject var profileVM: ProfileViewModel
    @State var hideButton = false
    @State var disableButton = false
    
    var body: some View {
        ZStack(alignment: .topTrailing) {
            CustomNavigationView(view: AnyView(Search(filteredItems: $filteredItems)), placeHolder: NSLocalizedString("search", comment:""), largeTitle: true, title: NSLocalizedString("inventory", comment:""),
                
                onSearch: { (txt) in
                // filterting Data...
                if txt != ""{
                    self.filteredItems = foods.filter{$0.name.lowercased().contains(txt.lowercased())}
                }
                else{
                    self.filteredItems = foods
                }
                
            }, onCancel: {
                // Do Your Own Code When Search And Canceled....
                self.filteredItems = foods
                self.hideButton = false
                self.disableButton = false
                
            }, onClick: {
                self.hideButton = true
                self.disableButton = true
            })
            .ignoresSafeArea()
            
            Button(action: {
                self.showingProfile.toggle()
                let token = UserToken(token: UserDefaults.standard.string(forKey: "token")!)
                profileVM.fetchMember(token: token)
            }) {
                Image(systemName: "person.crop.circle")
                    .font(.system(size: 30))
                    .opacity(hideButton ? 0 : 1)
            }.disabled(disableButton)
            .offset(x: 0, y: -10)
            .padding()
            .sheet(isPresented: $showingProfile, content: {ProfileView()})
        }
    }
}

struct SearchContainer_Previews: PreviewProvider {
    static var previews: some View {
        SearchContainer()
    }
}
