//
//  ToolbarViewController.swift
//  SBrowser
//
//  Created by James Magahern on 7/23/20.
//

import UIKit

public struct DarkModeControls
{
    public static func buttonImage(forDarkModeState enabled: Bool) -> UIImage {
        if enabled {
            return UIImage(systemName: "moon.circle.fill")!
        } else {
            return UIImage(systemName: "moon.circle")!
        }
    }
}

class ToolbarViewController: UIViewController
{
    let urlBar = URLBar()
    let toolbarView = ToolbarView()
    let scriptControllerIconView = ScriptControllerIconView()
    
    let shareButton =    ReliefButton()
    let darkModeButton = ReliefButton()
    let windowButton =   ReliefButton()
    let newTabButton =   ReliefButton()
    
    let backButton =     ReliefButton()
    let forwardButton =  ReliefButton()
    let navigationSegmentedButton = SegmentedReliefButton(children: [])
    
    var darkModeEnabled: Bool = false {
        didSet {
            darkModeButton.setImage(DarkModeControls.buttonImage(forDarkModeState: darkModeEnabled), for: .normal)
        }
    }
    
    init() {
        super.init(nibName: nil, bundle: nil)
        
        toolbarView.urlBar = urlBar
        
        // Dark mode button
        darkModeButton.setImage(DarkModeControls.buttonImage(forDarkModeState: darkModeEnabled), for: .normal)
        
        // Share button
        shareButton.setImage(UIImage(systemName: "square.and.arrow.up"), for: .normal)
        
        // Window button
        windowButton.setImage(UIImage(systemName: "rectangle.on.rectangle"), for: .normal)
        
        // Back button
        backButton.setImage(UIImage(systemName: "chevron.left"), for: .normal)
        
        // Forward button
        forwardButton.setImage(UIImage(systemName: "chevron.right"), for: .normal)
        
        // Navigation control
        navigationSegmentedButton.children = [ backButton, forwardButton ]
        
        // New tab button
        newTabButton.setImage(UIImage(systemName: "plus"), for: .normal)
        
        let toolbarAnimationDuration: TimeInterval = 0.3
        urlBar.textField.addAction(.init(handler: { [weak self] _ in
            guard let self, let parent else { return }
            
            // xxx: Not sure why I need to refer to parent here. This view controller isn't inheriting anything.
            if parent.traitCollection.horizontalSizeClass == .compact {
                UIView.animate(withDuration: toolbarAnimationDuration) { [unowned self] in
                    self.toolbarView.cancelButtonVisible = self.urlBar.textField.isFirstResponder
                }
            }
        }), for: [ .editingDidBegin, .editingDidEnd ])
        
        toolbarView.cancelButton.addAction(.init(handler: { [urlBar] action in
            urlBar.textField.resignFirstResponder()
        }), for: .touchUpInside)
        
        reconfigureButtons(for: traitCollection.horizontalSizeClass)
    }
    
    public func reconfigureButtons(for horizontalSizeClass: UIUserInterfaceSizeClass) {
        toolbarView.leadingButtonsView.removeAllButtonViews()
        toolbarView.trailingButtonsView.removeAllButtonViews()
        
        let spacerView = { () -> SpacerView in
            SpacerView(space: 20.0)
        }
        
        // Setup toolbar based on trait collection
        if horizontalSizeClass == .compact {
            toolbarView.trailingButtonsView.addButtonView(scriptControllerIconView)
            toolbarView.trailingButtonsView.addButtonView(newTabButton)
            toolbarView.trailingButtonsView.addButtonView(windowButton)
        } else {
            toolbarView.leadingButtonsView.addButtonView(navigationSegmentedButton)
            toolbarView.leadingButtonsView.addButtonView(spacerView())
            
            toolbarView.trailingButtonsView.addButtonView(shareButton)
            toolbarView.trailingButtonsView.addButtonView(spacerView())
            
            toolbarView.trailingButtonsView.addButtonView(darkModeButton)
            toolbarView.trailingButtonsView.addButtonView(scriptControllerIconView)
            
            toolbarView.trailingButtonsView.addButtonView(spacerView())
            
            toolbarView.trailingButtonsView.addButtonView(newTabButton)
            toolbarView.trailingButtonsView.addButtonView(windowButton)
        }
    }
    
    override func loadView() {
        self.view = toolbarView
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class SpacerView: UIView {
    internal var space: CGFloat = 0
    
    convenience init(space: CGFloat) {
        self.init(frame: .zero)
        self.space = space
    }
    
    override func sizeThatFits(_ size: CGSize) -> CGSize {
        CGSize(width: space, height: size.height)
    }
}
