//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//   playground ライブビューとコード間のメッセージハンドリング
//   playground BluetoothによるconnectionViewの表示

import UIKit
import SpriteKit
import PlaygroundSupport
import AVFoundation

public class DropViewController: UIViewController,PlaygroundLiveViewSafeAreaContainer  {
    private var mySKView = SKView()
    private var vstring = String()
    private var jewelType = Int() //宝石番号
    private var myScene = DropScene()
    public var label = UILabel()
    public var clrButton = UIButton()
    private var addedLayers = [CAShapeLayer]()  //描画したシェイプを保持
    private var dropCounter = [0,0,0,0,0,0,0,0,0,0]  //各列のカウンター

    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()
        jewelType = 1
        view.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
        // disable auto layout
        view.translatesAutoresizingMaskIntoConstraints = false
        
       //ビューを配置
        mySKView.isUserInteractionEnabled = true
        mySKView.clipsToBounds = true //はみ出さない様にする。
        mySKView.backgroundColor  = #colorLiteral(red: 0.1411764771, green: 0.3960784376, blue: 0.5647059083, alpha: 1)
        mySKView.layer.cornerRadius = 0
        //mySKView.showsFPS = true
        //mySKView.showsNodeCount = true
        mySKView.translatesAutoresizingMaskIntoConstraints  = false
        mySKView.frame.size = CGSize(width:200.0, height:205.0)
        myScene = DropScene(size: mySKView.frame.size)
        myScene.scaleMode = .aspectFit
        myScene.backgroundColor = SKColor.lightGray
        mySKView.allowsTransparency = true
        mySKView.presentScene(myScene)
        
        view.addSubview(mySKView)
        
        NSLayoutConstraint.activate([
            mySKView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor,constant: 20.0),
            mySKView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -20.0),
            mySKView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 50.0),
            mySKView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: -50)
            ])
        mySKView.backgroundColor = SKColor.red
        //
         // ボタンの位置とサイズを設定
        clrButton.frame = CGRect(x:20, y:80,
                        width:120, height:30)
         // ボタンのタイトルを設定
        clrButton.setTitle("クリア", for:UIControl.State.normal)
         // タイトルの色
        clrButton.setTitleColor(UIColor.blue, for: .normal)
         // ボタンのフォントサイズ
        clrButton.titleLabel?.font =  UIFont.systemFont(ofSize: 16)
         // 背景色
        clrButton.backgroundColor = UIColor.init(
            red:0.9, green: 0.9, blue: 0.9, alpha: 0.5)
         // タップされたときのaction
        clrButton.addTarget(self,
                            action: #selector(self.buttonTapped(sender:)),
                for: .touchUpInside)
         // Viewにボタンを追加
         self.view.addSubview(clrButton)
    }
    
    override public func viewWillAppear(_ animated: Bool) {
    }
    
    @objc func buttonTapped(sender : Any) {
           myScene.clear()
    }
    
}

extension DropViewController: PlaygroundLiveViewMessageHandler {
    //Playgroundページからメッセージを受け取る際の処理。

    public func receive(_ message: PlaygroundValue) {
        clrButton.isEnabled = false
        if case let .string(text) = message {
            if(text == "clear") { //クリア命令
                //全消し
                myScene.clear()
                dropCounter = [0,0,0,0,0,0,0,0,0,0]
                return
            }
            
            let arr:[String] = text.components(separatedBy: " ")

            if(arr.count == 2) {
                if(arr[0] == "drop") {
                    if(Int(arr[1])! < 1 || Int(arr[1])! > 10) {
                        return
                    }
                    if(dropCounter[Int(arr[1])!-1] < 10) {
                        dropCounter[Int(arr[1])!-1] += 1
                        if (jewelType == 0) {
                            myScene.dropZero(Int(arr[1])!)
                        } else if (jewelType == 1) {
                            myScene.dropRed(Int(arr[1])!)
                        } else if (jewelType == 2) {
                            myScene.dropGreen(Int(arr[1])!)
                        } else if (jewelType == 3) {
                            myScene.dropBlue(Int(arr[1])!)
                        }
                    }
                }
                
                if(arr[0] == "color") {
                    if(Int(arr[1])! < 4 && Int(arr[1])! >= 0) {
                    jewelType = Int(arr[1])!
                    } else {
                        jewelType = 1
                    }
                }
                return
            }

            if(arr.count == 4) {
                return
            }
    }
    }
   //Playgroundページにメッセージを送る際のサンプル。
    //public func tapped() {
    //    let message: PlaygroundValue = .string("Hello!")
        //myTextView.insertText("[send to your code]Hello!\n")
    //    send(message)
   // }
    
    
    public func liveViewMessageConnectionOpened() {
        clrButton.isEnabled = false
        mySKView.isUserInteractionEnabled = false
        // Implement this method to be notified when the live view message connection is opened.
        // The connection will be opened when the process running Contents.swift starts running and listening for messages.
    }
    
    public func liveViewMessageConnectionClosed() {
        clrButton.isEnabled = true
        mySKView.isUserInteractionEnabled = true
        // Implement this method to be notified when the live view message connection is closed.
        // The connection will be closed when the process running Contents.swift exits and is no longer listening for messages.
        // This happens when the user's code naturally finishes running, if the user presses Stop, or if there is a crash.
    }
}



