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

import UIKit
import PlaygroundSupport

public class SetSchoolViewController: UIViewController, PlaygroundLiveViewSafeAreaContainer {
    
    
    // Define each view
    private var settingView = UIView()
    private var schoolIdLabel = UILabel()
    private var schoolIdtextField = UITextField()
    private var webModeLabel = UILabel()
    private var webModetextField = UITextField()
    private var teacherModeLabel = UILabel()
    private var teacherModetextField = UITextField()
    private var explaneLabel = UILabel()
    //private var settingButton = UIButton()
    
    // User name variable
    private var schoolId: String? = nil
    private var webMode: String? = nil
    private var teacherMode: 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)
    }
    
    
    override public func viewDidLoad() {
        super.viewDidLoad()
        
        schoolIdLabel.text = "スクールID"
        webModeLabel.text = "Webモード"
        teacherModeLabel.text = "teacherモード"
        // PlaygroundKeyValueStoreからSchoolIdを取得
        if let keyValue = PlaygroundKeyValueStore.current["schoolId"],
            case .string(let storedSchoolId) = keyValue {
            schoolId = storedSchoolId
        } else {
            schoolId = nil
        }
        
        // PlaygroundKeyValueStoreからWebModeを取得
        if let keyValue = PlaygroundKeyValueStore.current["webMode"],
            case .string(let storedWebMode) = keyValue {
            webMode = storedWebMode
        } else {
            webMode = nil
        }
        
        // PlaygroundKeyValueStoreからteacherModeを取得
        if let keyValue = PlaygroundKeyValueStore.current["teacherMode"],
            case .string(let storedTeacherMode) = keyValue {
            teacherMode = storedTeacherMode
        } else {
            teacherMode = nil
        }
        
        // Setup numberLabel initial value
        schoolIdtextField.text = schoolId
        schoolIdtextField.isUserInteractionEnabled = false
        
        // Setup textField initial value
        webModetextField.text = webMode
        webModetextField.isUserInteractionEnabled = false
        
        // Setup textField initial value
        teacherModetextField.text = teacherMode
        teacherModetextField.isUserInteractionEnabled = false
        
        // 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(settingView)
        settingView.addSubview(explaneLabel)
        settingView.addSubview(schoolIdLabel)
        settingView.addSubview(schoolIdtextField)
        settingView.addSubview(webModeLabel)
        settingView.addSubview(webModetextField)
        settingView.addSubview(teacherModeLabel)
        settingView.addSubview(teacherModetextField)
        //settingView.addSubview(settingButton)

        
        explaneLabel.text = "　現在設定されている［スクールID］、［webモード］、［teacherモード］を表示しています。プログラムコードで変更する事ができます。"
        explaneLabel.textColor = UIColor.label
        explaneLabel.lineBreakMode = .byWordWrapping
        explaneLabel.numberOfLines = 0
        explaneLabel.font = UIFont.systemFont(ofSize: 20.0)
        
        schoolIdtextField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        schoolIdtextField.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)
        schoolIdtextField.textColor = UIColor.label
        schoolIdtextField.layer.cornerRadius = 10.0
        schoolIdtextField.layer.borderWidth = 1.0
        schoolIdtextField.clipsToBounds = true
        schoolIdtextField.setLeftPaddingPoints(10.0)
        schoolIdtextField.placeholder = "ユーザー名を入力"

        webModetextField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        webModetextField.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)
        webModetextField.textColor = UIColor.label
        webModetextField.layer.cornerRadius = 10.0
        webModetextField.layer.borderWidth = 1.0
        webModetextField.clipsToBounds = true
        webModetextField.setLeftPaddingPoints(10.0)
        webModetextField.placeholder = "On または Off を入力"
        
        teacherModetextField.frame = CGRect(x: 0, y: 0, width: 200, height: 50)
        teacherModetextField.backgroundColor = UIColor.systemBackground.withAlphaComponent(0.5)
        teacherModetextField.textColor = UIColor.label
        teacherModetextField.layer.cornerRadius = 10.0
        teacherModetextField.layer.borderWidth = 1.0
        teacherModetextField.clipsToBounds = true
        teacherModetextField.setLeftPaddingPoints(10.0)
        teacherModetextField.placeholder = "On または Off を入力"
        
        settingView.clipsToBounds = true //はみ出さない様にする。
        settingView.backgroundColor = UIColor { (traitCollection: UITraitCollection) -> UIColor in
            if traitCollection.userInterfaceStyle == .dark {
                return UIColor(red: 0.18, green: 0.57, blue: 0.85, alpha: 1.0) // ダークモード用の水色
            } else {
                return UIColor(red: 0.239, green: 0.675, blue: 0.969, alpha: 1.0) // ライトモード用の水色
            }
        }
        settingView.layer.cornerRadius = 0
        
        // Auto Layout設定
        settingView.translatesAutoresizingMaskIntoConstraints = false
        explaneLabel.translatesAutoresizingMaskIntoConstraints = false
        schoolIdLabel.translatesAutoresizingMaskIntoConstraints = false
        schoolIdtextField.translatesAutoresizingMaskIntoConstraints = false
        webModeLabel.translatesAutoresizingMaskIntoConstraints = false
        webModetextField.translatesAutoresizingMaskIntoConstraints = false
        teacherModeLabel.translatesAutoresizingMaskIntoConstraints = false
        teacherModetextField.translatesAutoresizingMaskIntoConstraints = false
        //settingButton.translatesAutoresizingMaskIntoConstraints = false

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

            // explaneLabelの制約
            explaneLabel.topAnchor.constraint(equalTo: settingView.topAnchor, constant: 40),
            explaneLabel.leadingAnchor.constraint(equalTo: settingView.leadingAnchor, constant: 20),
            explaneLabel.trailingAnchor.constraint(equalTo: settingView.trailingAnchor, constant: -20),
            explaneLabel.heightAnchor.constraint(greaterThanOrEqualToConstant: 80),

            // schoolIdLabelの制約
            schoolIdLabel.topAnchor.constraint(equalTo: explaneLabel.bottomAnchor, constant: 20),
            schoolIdLabel.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            schoolIdLabel.widthAnchor.constraint(equalToConstant: 240),
            schoolIdLabel.heightAnchor.constraint(equalToConstant: 50),
            
            // schoolIdtextFieldの制約
            schoolIdtextField.topAnchor.constraint(equalTo: schoolIdLabel.bottomAnchor, constant: 0),
            schoolIdtextField.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            schoolIdtextField.widthAnchor.constraint(equalToConstant: 240),
            schoolIdtextField.heightAnchor.constraint(equalToConstant: 50),
            
            // webModeLabelの制約
            webModeLabel.topAnchor.constraint(equalTo: schoolIdtextField.bottomAnchor, constant: 20),
            webModeLabel.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            webModeLabel.widthAnchor.constraint(equalToConstant: 240),
            webModeLabel.heightAnchor.constraint(equalToConstant: 50),
            
            // webModetextFieldの制約
            webModetextField.topAnchor.constraint(equalTo: webModeLabel.bottomAnchor, constant: 0),
            webModetextField.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            webModetextField.widthAnchor.constraint(equalToConstant: 240),
            webModetextField.heightAnchor.constraint(equalToConstant: 50),
            
            // webModeLabelの制約
            teacherModeLabel.topAnchor.constraint(equalTo: webModetextField.bottomAnchor, constant: 20),
            teacherModeLabel.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            teacherModeLabel.widthAnchor.constraint(equalToConstant: 240),
            teacherModeLabel.heightAnchor.constraint(equalToConstant: 50),
            
            // webModetextFieldの制約
            teacherModetextField.topAnchor.constraint(equalTo: teacherModeLabel.bottomAnchor, constant: 0),
            teacherModetextField.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            teacherModetextField.widthAnchor.constraint(equalToConstant: 240),
            teacherModetextField.heightAnchor.constraint(equalToConstant: 50),
            
            // settingButtonの制約
            //settingButton.topAnchor.constraint(equalTo: teacherModetextField.bottomAnchor, constant: 20),
            //settingButton.centerXAnchor.constraint(equalTo: settingView.centerXAnchor),
            //settingButton.widthAnchor.constraint(equalToConstant: 140),
            //settingButton.heightAnchor.constraint(equalToConstant: 50)
        ])

    }
    
    @objc func tapSettingButton(_ sender: UIButton) {
        var saved = false
        var invalidInput = false

        if let text = schoolIdtextField.text, !text.isEmpty {
            PlaygroundKeyValueStore.current["schoolId"] = .string(text)
            saved = true
        }

        if let modeText = webModetextField.text, !modeText.isEmpty {
            if modeText == "On" || modeText == "Off" {
                PlaygroundKeyValueStore.current["webMode"] = .string(modeText)
                saved = true
            } else {
                invalidInput = true
            }
        }
        
        if let modeText = teacherModetextField.text, !modeText.isEmpty {
            if modeText == "On" || modeText == "Off" {
                PlaygroundKeyValueStore.current["teacherMode"] = .string(modeText)
                saved = true
            } else {
                invalidInput = true
            }
        }
        
        if invalidInput {
            let alert = UIAlertController(title: "エラー", message: "Webモードには 'On' または 'Off' のみ入力可能です。", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alert, animated: true, completion: nil)
        } else if saved {
            let alert = UIAlertController(title: "保存完了", message: "設定が保存されました。", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            present(alert, animated: true, completion: nil)
        }
    }
}

extension SetSchoolViewController: PlaygroundLiveViewMessageHandler {
    // Receive messages from the playground page
    
    public func receive(_ message: PlaygroundValue) {
        // Setup numberLabel initial value
        if case let .string(text) = message {
            let arr:[String] = text.components(separatedBy: " ")
            if(arr[0] == "update") {
                // PlaygroundKeyValueStoreからschoolIDを取得
                if let keyValue = PlaygroundKeyValueStore.current["schoolId"],
                    case .string(let storedSchoolId) = keyValue {
                    schoolId = storedSchoolId
                    schoolIdtextField.text = schoolId
                } else {
                    schoolId = nil
                }
                // PlaygroundKeyValueStoreからwebModeを取得
                if let keyValue = PlaygroundKeyValueStore.current["webMode"],
                    case .string(let storedWebMode) = keyValue {
                    webMode = storedWebMode
                    webModetextField.text = webMode
                } else {
                    webMode = nil
                }
                // PlaygroundKeyValueStoreからteacherModeを取得
                if let keyValue = PlaygroundKeyValueStore.current["teacherMode"],
                    case .string(let storedTeacherMode) = keyValue {
                    teacherMode = storedTeacherMode
                    teacherModetextField.text = teacherMode
                } else {
                    teacherMode = nil
                }
                
                return
            }
        }
        
        
        
        
    }
    // Send messages to the playground page as a sample
    // public func tapped() { send(message) }
}
