//
//  CodeEditorSettingsViewController.swift
//  SBrowser
//
//  Copyright © 2021 Apple Inc. All rights reserved.
//

import UIKit

class CodeEditorSettingsView: UIView
{
    public let textView = UITextView()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        self.backgroundColor = UIColor.systemBackground
        
        textView.backgroundColor = UIColor.secondarySystemBackground
        textView.font = .monospacedSystemFont(ofSize: 12.0, weight: .regular)
        textView.autocorrectionType = .no
        textView.autocapitalizationType = .none
        textView.smartDashesType = .no
        textView.smartQuotesType = .no
        addSubview(textView)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        textView.frame = bounds.inset(by: layoutMargins).insetBy(dx: 0.0, dy: 18.0)
    }
}

class CodeEditorSettingsViewController: UIViewController, UITextViewDelegate
{
    private let settingsKeypath: ReferenceWritableKeyPath<Settings, String>
    
    private var saveTimer: Timer?
    private let settingsView = CodeEditorSettingsView(frame: .zero)
    
    public init(settingsKeypath: ReferenceWritableKeyPath<Settings, String>) {
        self.settingsKeypath = settingsKeypath
        super.init(nibName: nil, bundle: nil)
        
        if settingsKeypath == \.userStylesheet {
            tabBarItem.title = "Stylesheet"
            tabBarItem.image = UIImage(systemName: "newspaper")
        } else if settingsKeypath == \.userScript {
            tabBarItem.title = "Script"
            tabBarItem.image = UIImage(systemName: "applescript")
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func loadView() {
        self.view = settingsView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        settingsView.textView.delegate = self
        settingsView.textView.text = Settings.shared[keyPath: settingsKeypath]
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        saveContents()
    }
    
    private func saveContents() {
        Settings.shared[keyPath: settingsKeypath] = settingsView.textView.text!
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        if self.saveTimer?.isValid == true { return true }
        
        self.saveTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: false, block: { [weak self] timer in
            self?.saveContents()
        })
        
        return true
    }
}
