//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//   playground 番号とユーザー名を登録するビュー
//   playground BluetoothによるconnectionViewの表示

import UIKit
import PlaygroundSupport

public class SetNameViewController: UIViewController, PlaygroundLiveViewSafeAreaContainer, TablePickerViewControllerDelegate {
    
    // Delegate method for TablePickerViewController
    func didSelectNumber(_ number: Int) {
        numberLabel.text = "\(number)"
    }
    
    // Define each view
    private var nameView = UIView()
    private var textField = UITextField()
    private var explaneLabel = UILabel()
    private var numberLabel = UILabel()
    private var settingButton = UIButton()
    
    // User name variable
    private var userName: String? = nil
    private var userNumber: String? = nil
    
    public required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)!
    }
    
    public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    @objc func tapSettingButton(_ sender: UIButton) {
        var saved = false
        
        if let text = textField.text, !text.isEmpty {
            PlaygroundKeyValueStore.current["userName"] = .string(text)
            saved = true
        }
        
        if let numberText = numberLabel.text, numberText != "-" {
            PlaygroundKeyValueStore.current["userNumber"] = .string(numberText)
            saved = true
        }
        
        if saved {
            let alert = UIAlertController(title: "保存完了", message: "設定が保存されました。", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alert, animated: true, completion: nil)
        }
    }
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        
        // PlaygroundKeyValueStoreからユーザー名を取得
        if let keyValue = PlaygroundKeyValueStore.current["userName"],
            case .string(let storedUserName) = keyValue {
            userName = storedUserName
        } else {
            userName = nil
        }
        
        // PlaygroundKeyValueStoreから番号を取得
        if let keyValue = PlaygroundKeyValueStore.current["userNumber"],
            case .string(let storedNumber) = keyValue {
            userNumber = storedNumber
        } else {
            userNumber = nil
        }
        
        // Setup numberLabel initial value
        numberLabel.text = userNumber ?? "-"
        
        // Setup textField initial value
        textField.text = userName
        
        // UIButtonを生成
        settingButton.frame = CGRect(x: 120, y: 100, width: 80, height: 30)
        settingButton.setTitle("保存する", for: UIControl.State.normal)
        settingButton.titleLabel!.font = UIFont(name: "HiraKakuProN-W6", size: 20)
        settingButton.setTitleColor(UIColor.black, for: UIControl.State.normal)
        settingButton.layer.cornerRadius = 5
        settingButton.backgroundColor = UIColor(red: 0.97, green: 0.97, blue: 0.97, alpha: 1.0)
        settingButton.layer.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.25).cgColor
        settingButton.layer.shadowOffset = CGSize(width: 0.0, height: 2.0)
        settingButton.layer.shadowOpacity = 1.0
        settingButton.layer.shadowRadius = 0.0
        settingButton.layer.masksToBounds = false
        settingButton.layer.cornerRadius = 4.0
        settingButton.addTarget(self, action: #selector(tapSettingButton(_:)), for: UIControl.Event.touchUpInside)

        view.addSubview(nameView)
        nameView.addSubview(textField)
        nameView.addSubview(settingButton)
        nameView.addSubview(explaneLabel)
        nameView.addSubview(numberLabel)
        
        explaneLabel.text = "　現在設定されている［番号］と［ユーザー名］を表示しています。変更する場合は、入力欄の値を変更して、［保存する］ボタンを押してください。"
        explaneLabel.textColor = UIColor.label
        explaneLabel.lineBreakMode = .byWordWrapping
        explaneLabel.numberOfLines = 0
        explaneLabel.font = UIFont.systemFont(ofSize: 20.0)
        
        numberLabel.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        numberLabel.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)

        numberLabel.textColor = UIColor.label
        numberLabel.layer.borderWidth = 1.0
        numberLabel.layer.cornerRadius = 10.0
        numberLabel.clipsToBounds = true
        numberLabel.textAlignment = .center
        numberLabel.isUserInteractionEnabled = true // ユーザーインタラクションを有効にする
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(showNumberPicker))
        numberLabel.addGestureRecognizer(tapGesture)

        textField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        textField.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)
        textField.textColor = UIColor.label
        textField.layer.cornerRadius = 10.0
        textField.layer.borderWidth = 1.0
        textField.clipsToBounds = true
        textField.setLeftPaddingPoints(10.0)
        textField.placeholder = "ユーザー名を入力"
        
        nameView.clipsToBounds = true //はみ出さない様にする。
        nameView.backgroundColor = UIColor { (traitCollection: UITraitCollection) -> UIColor in
            if traitCollection.userInterfaceStyle == .dark {
                return UIColor(red: 0.12, green: 0.6, blue: 0.4, alpha: 1.0) // ダークモード用の黄緑色
            } else {
                return UIColor(red: 0.239, green: 0.969, blue: 0.675, alpha: 1.0) // ライトモード用の黄緑色
            }
        }
        nameView.layer.cornerRadius = 0
        
        // Auto Layout設定
        nameView.translatesAutoresizingMaskIntoConstraints = false
        explaneLabel.translatesAutoresizingMaskIntoConstraints = false
        numberLabel.translatesAutoresizingMaskIntoConstraints = false
        textField.translatesAutoresizingMaskIntoConstraints = false
        settingButton.translatesAutoresizingMaskIntoConstraints = false

        NSLayoutConstraint.activate([
            // nameViewの制約
            nameView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 0),
            nameView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: 0),
            nameView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 0),
            nameView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: 0),

            // explaneLabelの制約
            explaneLabel.topAnchor.constraint(equalTo: nameView.topAnchor, constant: 40),
            explaneLabel.leadingAnchor.constraint(equalTo: nameView.leadingAnchor, constant: 20),
            explaneLabel.trailingAnchor.constraint(equalTo: nameView.trailingAnchor, constant: -20),
            explaneLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 80),
            // numberLabelの制約
            numberLabel.topAnchor.constraint(equalTo: explaneLabel.bottomAnchor, constant: 20),
            numberLabel.trailingAnchor.constraint(equalTo: textField.leadingAnchor, constant: -20), // ここに間隔を追加
            numberLabel.widthAnchor.constraint(equalToConstant: 50),
            numberLabel.heightAnchor.constraint(equalToConstant: 50),
            // textViewの制約
            textField.topAnchor.constraint(equalTo: explaneLabel.bottomAnchor, constant: 20),
            textField.centerXAnchor.constraint(equalTo: nameView.centerXAnchor),
            textField.widthAnchor.constraint(equalToConstant: 240),
            textField.heightAnchor.constraint(equalToConstant: 50),
            // settingButtonの制約
            settingButton.topAnchor.constraint(equalTo: textField.bottomAnchor, constant: 20),
            settingButton.centerXAnchor.constraint(equalTo: nameView.centerXAnchor),
            settingButton.widthAnchor.constraint(equalToConstant: 140),
            settingButton.heightAnchor.constraint(equalToConstant: 50)
        ])
    }

    
    @objc func showNumberPicker() {
        let alert = UIAlertController(title: "番号選択", message: nil, preferredStyle: .alert)
        
        let pickerVC = TablePickerViewController()
        pickerVC.delegate = self
        
        let height: NSLayoutConstraint = NSLayoutConstraint(item: pickerVC.view!, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 250)
        pickerVC.view.addConstraint(height)
        
        alert.setValue(pickerVC, forKey: "contentViewController")
        
        alert.addAction(UIAlertAction(title: "キャンセル", style: .cancel, handler: nil))
        
        present(alert, animated: true, completion: nil)
    }
}


extension SetNameViewController: PlaygroundLiveViewMessageHandler {
    // Receive messages from the playground page
    // public func receive(_ message: PlaygroundValue) {}
    // Send messages to the playground page as a sample
    // public func tapped() { send(message) }
}
