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

import UIKit
import PlaygroundSupport
import AVFoundation

public class TileImageViewController: UIViewController,PlaygroundLiveViewSafeAreaContainer,AVAudioPlayerDelegate {
    private var audioPlayer: AVAudioPlayer?
    private var myCanvasView  = UIView()
    private var containerView = UIView()
    private var imageView11 = UIImageView()
    private var imageView12 = UIImageView()
    private var imageView21 = UIImageView()
    private var imageView22 = UIImageView()
    private var vstring = String()
    private var addedLayers = [CAShapeLayer]()  //描画したシェイプを保持
    private var lineColor = UIColor()
    private var lineWidth = CGFloat()
    private var correct = [Bool()] //正解したフラグ
    private var completed = false //完成した

    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){

        // タップviewの色を変える (Red <=> Blue)
        /*if(myCanvasView.backgroundColor  == .red) {
            myCanvasView.backgroundColor = .blue
        }
        else {
            myCanvasView.backgroundColor = .red
        }*/
        // ボタンがタップされたときに音楽を再生します。
        if completed {
            if let player = audioPlayer {
                if player.isPlaying {
                    // 既に再生中の場合、停止させて再生位置をリセットします。
                    player.stop()
                    player.currentTime = 0
                }
                // 音楽を再生します。
                player.play()
            }
        }
    }

    override public func viewDidLoad() {
        super.viewDidLoad()
        for _ in 1..<6 { //1〜5まで追加
            correct.append(false)
        }

        imageView11 = UIImageView(image: UIImage(named: "blankImage")!)
        imageView12 = UIImageView(image: UIImage(named: "blankImage")!)
        imageView21 = UIImageView(image: UIImage(named: "blankImage")!)
        imageView22 = UIImageView(image: UIImage(named: "blankImage")!)
        
        containerView = UIView(frame: CGRect(x: 0, y: 0, width: 400, height: 400))
        containerView.contentMode = .scaleAspectFit
        
        // ジェスチャーの生成
        let gesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGesture(_:)))
        myCanvasView.addGestureRecognizer(gesture)
        myCanvasView.isUserInteractionEnabled = true
        
        lineColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
        lineWidth = 1.0
        view.backgroundColor = #colorLiteral(red: 0.2745098174, green: 0.4862745106, blue: 0.1411764771, alpha: 1)
        // disable auto layout
        view.translatesAutoresizingMaskIntoConstraints = false
        
       //キャンバスビューを配置
        view.addSubview(myCanvasView)
        myCanvasView.clipsToBounds = true //はみ出さない様にする。
        //myCanvasView.backgroundColor  = #colorLiteral(red: 0.2549019754, green: 0.2745098174, blue: 0.3019607961, alpha: 1)
        myCanvasView.layer.cornerRadius = 0
        myCanvasView.translatesAutoresizingMaskIntoConstraints  = false
        myCanvasView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 50).isActive = true
        myCanvasView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: -50).isActive = true
        myCanvasView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 20).isActive = true
        myCanvasView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -20).isActive = true
        myCanvasView.addSubview(containerView)
        
        containerView.translatesAutoresizingMaskIntoConstraints  = false
        containerView.centerXAnchor.constraint(equalTo: myCanvasView.centerXAnchor, constant: 0).isActive = true
        containerView.centerYAnchor.constraint(equalTo: myCanvasView.centerYAnchor, constant: 0).isActive = true
        containerView.widthAnchor.constraint(equalTo: liveViewSafeAreaGuide.heightAnchor, constant: -200).isActive = true
        containerView.heightAnchor.constraint(equalTo: containerView.widthAnchor, constant: 0).isActive = true
        containerView.backgroundColor = #colorLiteral(red: 0.2588235438, green: 0.7568627596, blue: 0.9686274529, alpha: 1)
        containerView.contentMode = .scaleAspectFit
        containerView.addSubview(imageView11)
        containerView.addSubview(imageView12)
        containerView.addSubview(imageView21)
        containerView.addSubview(imageView22)
        
        imageView11.translatesAutoresizingMaskIntoConstraints  = false
        imageView11.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0).isActive = true
        imageView11.bottomAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0).isActive = true
        imageView11.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0).isActive = true
        imageView11.trailingAnchor.constraint(equalTo: containerView.centerXAnchor, constant: 0).isActive = true
        imageView12.translatesAutoresizingMaskIntoConstraints  = false
        imageView12.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0).isActive = true
        imageView12.bottomAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0).isActive = true
        imageView12.leadingAnchor.constraint(equalTo: containerView.centerXAnchor, constant: 0).isActive = true
        imageView12.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0).isActive = true
        imageView21.translatesAutoresizingMaskIntoConstraints  = false
        imageView21.topAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0).isActive = true
        imageView21.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0).isActive = true
        imageView21.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0).isActive = true
        imageView21.trailingAnchor.constraint(equalTo: containerView.centerXAnchor, constant: 0).isActive = true
        imageView22.translatesAutoresizingMaskIntoConstraints  = false
        imageView22.topAnchor.constraint(equalTo: containerView.centerYAnchor, constant: 0).isActive = true
        imageView22.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0).isActive = true
        imageView22.leadingAnchor.constraint(equalTo: containerView.centerXAnchor, constant: 0).isActive = true
        imageView22.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0).isActive = true
        
        // MP3ファイルのパスを取得します（プロジェクトに追加された場合、ファイル名を指定するだけで良いです）。
        if let path = Bundle.main.path(forResource: "xmasVoice", ofType: "mp3") {
            let url = URL(fileURLWithPath: path)

            do {
                // AVAudioPlayerを初期化してMP3ファイルを準備します。
                audioPlayer = try AVAudioPlayer(contentsOf: url)
                audioPlayer?.prepareToPlay()
            } catch {
                // エラーハンドリングを行います。
                print("音楽の読み込みエラー: \(error.localizedDescription)")
            }
        }
        
    }
    
    override public func viewWillAppear(_ animated: Bool) {
    }
}

extension TileImageViewController: PlaygroundLiveViewMessageHandler {
    //Playgroundページからメッセージを受け取る際の処理。
    public func receive(_ message: PlaygroundValue) {
        if case let .string(text) = message {
            
            let arr:[String] = text.components(separatedBy: " ")
            if(text == "clear") { //クリア
                for i in 1..<6 {
                    correct[i] = false
                }
                completed = false
                imageView11.image = UIImage(named: "blankImage")!
                imageView12.image = UIImage(named: "blankImage")!
                imageView21.image = UIImage(named: "blankImage")!
                imageView22.image = UIImage(named: "blankImage")!
                return
            }
            if(arr.count == 2) {
                if(arr[0] == "setImage") {
                    var number = 0
                    if let n = Int(arr[1]) {
                        number = n
                    }
                    switch number {
                    case 1:
                        UIView.transition(with: imageView11,
                                                 duration: 2.0,
                                                 options: .transitionCrossDissolve,
                                                 animations: {
                            self.imageView11.image = UIImage(imageLiteralResourceName: "kiki-11")
                               }, completion: nil)
                        correct[1] = true
                    case 2:
                        UIView.transition(with: imageView12,
                                                 duration: 2.0,
                                                 options: .transitionCrossDissolve,
                                                 animations: {
                            self.imageView12.image = UIImage(imageLiteralResourceName: "kiki-12")
                               }, completion: nil)
                        correct[2] = true
                    case 3:
                        UIView.transition(with: imageView21,
                                                 duration: 2.0,
                                                 options: .transitionCrossDissolve,
                                                 animations: {
                            self.imageView21.image = UIImage(imageLiteralResourceName: "kiki-21")
                               }, completion: nil)
                        correct[3] = true
                    case 4:
                        UIView.transition(with: imageView22,
                                                 duration: 2.0,
                                                 options: .transitionCrossDissolve,
                                                 animations: {
                            self.imageView22.image = UIImage(imageLiteralResourceName: "kiki-22")
                               }, completion: nil)
                        correct[4] = true
                    case 5:
                        correct[5] = true
                    default:
                        break
                    }
                    var comp = true
                    for i in 1..<6 {
                        if correct[i] == false {
                            comp = false
                        }
                    }
                    completed = comp
                }
            }
        }
    }
    //Playgroundページにメッセージを送る際のサンプル。
    //public func tapped() {
    //    let message: PlaygroundValue = .string("Hello!")
    //myTextView.insertText("[send to your code]Hello!\n")
    //    send(message)
    // }
    
}

