//
//  See LICENSE folder for this template’s licensing information.
//
//  Abstract:
//  A source file which is part of the auxiliary module named "BookCore".
//  Provides the implementation of the "always-on" live view.
//

import Foundation
import UIKit
import PlaygroundSupport
import PhotosUI

public class PhotoViewController: UIViewController, PlaygroundLiveViewMessageHandler, PlaygroundLiveViewSafeAreaContainer, UIImagePickerControllerDelegate, PHPickerViewControllerDelegate {
    
    private var myIpTextView  = UITextView()
    private let photoImageView = UIImageView()
    private let textView = UITextView()
    private var vstring = String()
    private var textColor = UIColor()

    
    override public func viewDidLoad() {
        super.viewDidLoad()

        //view.backgroundColor = .systemCyan
        view.backgroundColor = .black
        // disable auto layout
        view.translatesAutoresizingMaskIntoConstraints = false

        //自分のIPアドレス表示ビューを配置
        myIpTextView.font = UIFont.monospacedSystemFont(ofSize: 20, weight: .medium)
        myIpTextView.isEditable = false
         view.addSubview(myIpTextView)
        myIpTextView.textColor = .white
        // textColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
        myIpTextView.backgroundColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 0.007892219388)
        myIpTextView.translatesAutoresizingMaskIntoConstraints  = false
        myIpTextView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 10).isActive = true
        myIpTextView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 40).isActive = true
        myIpTextView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 20).isActive = true
        myIpTextView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -20).isActive = true
        //このデバイスのipアドレスを取得してipAddressTextViewに表示
        myIpTextView.text = "このデバイスのIPアドレス：" + getIPV4Address()
        
        //ライト表示用のimageビューを配置
        photoImageView.frame = view.bounds
        photoImageView.image = UIImage(named: "defaultPhoto.jpg")
        photoImageView.contentMode = .scaleAspectFill
        view.addSubview(photoImageView)
        photoImageView.isUserInteractionEnabled = true
        photoImageView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(imageTapped)))
        //lightImageView.backgroundColor  = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.5)
        photoImageView.layer.cornerRadius = 10
        
        photoImageView.translatesAutoresizingMaskIntoConstraints  = false
        photoImageView.topAnchor.constraint(equalTo: myIpTextView.bottomAnchor, constant: 10).isActive = true
        photoImageView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: -50).isActive = true
        photoImageView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 20).isActive = true
        photoImageView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -20).isActive = true
        
        //メッセージ表示用のビューを配置
        textView.font = UIFont.monospacedSystemFont(ofSize: 20, weight: .medium)
        textView.isEditable = false
        view.addSubview(textView)
        //textView.textColor = .white
        textView.translatesAutoresizingMaskIntoConstraints  = false
        textView.topAnchor.constraint(equalTo: photoImageView.bottomAnchor, constant: 10).isActive = true
        textView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: 0).isActive = true
        textView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 20).isActive = true
        textView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: -20).isActive = true
    }
    
    /*
    public func liveViewMessageConnectionOpened() {
        // 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() {
        // 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.
        textView.text = ""
    }
    
    public func receive(_ message: PlaygroundValue) {
        // Implement this method to receive messages sent from the process running Contents.swift.
        // This method is *required* by the PlaygroundLiveViewMessageHandler protocol.
        // Use this method to decode any messages sent as PlaygroundValue values and respond accordingly.
        if case let .string(text) = message {
            if text.hasPrefix("GET-PHOTO") {
               let photoData : Data = photoImageView.image!.jpegData(compressionQuality: 1)!
               let message: PlaygroundValue = .data(photoData)
               send(message)
                //textView.text = textView.text + "イメージを渡しました\n"
            } else {
                textView.text = textView.text + "\(text)\n"
            }
            
        }
    }
    //写真をタップした時にピッカーを呼び出す
    @objc func imageTapped(sender : Any) {
        var config: PHPickerConfiguration
        config = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
        config.selectionLimit = 1
        config.filter = .images
        // Avoid transcoding, if possible.
        config.preferredAssetRepresentationMode = .current
        let picker = PHPickerViewController(configuration: config)
        picker.modalPresentationStyle = .overFullScreen
        picker.delegate = self
        self.present(picker, animated: true)
    }
    //フォトピッカー
    public func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        picker.dismiss(animated: true, completion: nil)
        // 1枚だけの処理にしているので要注意！
        // 1枚目の写真のみをプロバイダにする。
        guard let provider = results.first?.itemProvider else { return }
        // 1枚目の写真のタイプ識別子
        //guard let typeIdentifer = provider.registeredTypeIdentifiers.first else { return }

        if provider.canLoadObject(ofClass: UIImage.self) {
            provider.loadObject(ofClass: UIImage.self) { [weak self] data, error  in
                if let firstImage = data as? UIImage {
                    //TODO イメージ取得後の処理
                    DispatchQueue.main.async { [self] in
                        //イメージビューの画像を設定
                        self!.photoImageView.image = firstImage
                        //コードに変更した画像を渡す
                        let photoData : Data = self!.photoImageView.image!.jpegData(compressionQuality: 1)!
                        let message: PlaygroundValue = .data(photoData)
                        self!.send(message)
                        //self!.textView.text = self!.textView.text + "イメージを渡しました\n"
                    }
                }
            }
        }
    }
}
