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

import UIKit
import PlaygroundSupport

public class CanvasViewController: UIViewController,PlaygroundLiveViewSafeAreaContainer  {
    private var myCanvasView  = UIView()
    private var vstring = String()
    private var label = UILabel()
    private var addedLayers = [CAShapeLayer]()  //描画したシェイプを保持
    private var lineColor = UIColor()
    private var lineWidth = CGFloat()

    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 tapGesture(_ sender: UITapGestureRecognizer){
        let tapPoint = sender.location(in:myCanvasView)
        let x = Int(tapPoint.x) - Int(myCanvasView.frame.width/2.0)
        let y = -Int(tapPoint.y) + Int(myCanvasView.frame.height/2.0)
        label.text = "x:\(x) , y:\(y)"
        // タップviewの色を変える (Red <=> Blue)
        /*if(myCanvasView.backgroundColor  == .red) {
            myCanvasView.backgroundColor = .blue
        }
        else {
            myCanvasView.backgroundColor = .red
        }*/
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        // ジェスチャーの生成
        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGesture(_:)))
        myCanvasView.addGestureRecognizer(gesture)
        myCanvasView.isUserInteractionEnabled = true
        //座標表示ラベルをセット
        label.frame = CGRect(x: 0, y: 0, width: 200, height: 20)
        myCanvasView.addSubview(label)
        
        lineColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        lineWidth = 1.0
        view.backgroundColor = #colorLiteral(red: 0.1764705926, green: 0.4980392158, blue: 0.7568627596, alpha: 1)
        // disable auto layout
        view.translatesAutoresizingMaskIntoConstraints = false
        
       //スクロールビューを配置
        //myCanvasView.isScrollEnabled = true
        view.addSubview(myCanvasView)
        myCanvasView.clipsToBounds = true //はみ出さない様にする。
        myCanvasView.backgroundColor  = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        myCanvasView.layer.cornerRadius = 0
        myCanvasView.translatesAutoresizingMaskIntoConstraints  = false
        myCanvasView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 40).isActive = true
        myCanvasView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: -40).isActive = true
        myCanvasView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 20).isActive = true
        myCanvasView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -20).isActive = true
    }
    
    override public func viewWillAppear(_ animated: Bool) {
    }
    
}

extension CanvasViewController: PlaygroundLiveViewMessageHandler {
    //Playgroundページからメッセージを受け取る際の処理。
    public func receive(_ message: PlaygroundValue) {
        if case let .string(text) = message {
            if(text == "clear") { //クリア命令
                // 全消し
                self.addedLayers.forEach {
                    $0.removeFromSuperlayer()
                }
                //色をリセット
                lineColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
                //線の太さをリセット
                lineWidth = 1.0
                //座標値の表示を消去
                label.text = ""
                return
            }
            let arr:[String] = text.components(separatedBy: " ")
            
            if(arr.count == 2) {
                if(arr[0] == "width") {
                    let w = CGFloat(Double(arr[1])!)
                    lineWidth = w
                }
                return
            }
            
            if(arr.count == 4) {
                if(arr[0] == "circle") {
                    let x = CGFloat(Double(arr[1])!) + self.myCanvasView.frame.width/2.0
                    let y = -CGFloat(Double(arr[2])!) + self.myCanvasView.frame.height/2.0
                    let r = CGFloat(Double(arr[3])!)
                    let circlePath = UIBezierPath()
                    circlePath.addArc(withCenter: CGPoint(x: x, y: y), // 中心
                                      radius: r, // 半径
                                      startAngle: 0, // 開始角度
                                      endAngle: .pi * 2.0, // 終了角度
                                      clockwise: true) // 時計回り
                    let lineLayer = CAShapeLayer()
                    lineLayer.path = circlePath.cgPath
                    lineLayer.strokeColor = lineColor.cgColor
                    lineLayer.lineWidth = lineWidth
                    lineLayer.fillColor = #colorLiteral(red: 0.9999960065, green: 1, blue: 1, alpha: 0) // 塗り色は透明に
                    self.myCanvasView.layer.addSublayer(lineLayer)
                    // ここで保持しておく
                    self.addedLayers.append(lineLayer)
                    return
                }
            }
            
            if(arr.count == 5) {
                if(arr[0] == "line") {
                    let x1 = CGFloat(Double(arr[1])!) + self.myCanvasView.frame.width/2.0
                    let y1 = -CGFloat(Double(arr[2])!) + self.myCanvasView.frame.height/2.0
                    let x2 = CGFloat(Double(arr[3])!) + self.myCanvasView.frame.width/2.0
                    let y2 = -CGFloat(Double(arr[4])!) + self.myCanvasView.frame.height/2.0
                    //myTextView.insertText("LINE描画\n")
                    let frPoint = CGPoint(x: x1, y: y1)
                    let toPoint = CGPoint(x: x2, y: y2)
                    let linePath = UIBezierPath()
                    linePath.move(to: frPoint)
                    linePath.addLine(to: toPoint)
                    let lineLayer = CAShapeLayer()
                    lineLayer.path = linePath.cgPath
                    lineLayer.strokeColor = lineColor.cgColor
                    lineLayer.lineWidth = lineWidth
                    self.myCanvasView.layer.addSublayer(lineLayer)
                    // ここで保持しておく
                    self.addedLayers.append(lineLayer)
                    return
                }
                
                if(arr[0] == "color") {
                    let r = CGFloat(Double(arr[1])!)
                    let g = CGFloat(Double(arr[2])!)
                    let b = CGFloat(Double(arr[3])!)
                    let a = CGFloat(Double(arr[4])!)
                    lineColor = UIColor(red: r, green: g, blue: b, alpha: a)
                }
            }
        }
    }
    //Playgroundページにメッセージを送る際のサンプル。
    //public func tapped() {
    //    let message: PlaygroundValue = .string("Hello!")
    //myTextView.insertText("[send to your code]Hello!\n")
    //    send(message)
    // }
    
}

