//
//  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
import PDFKit
import AudioToolbox

public class PDFandPhotoViewController: UIViewController, PlaygroundLiveViewMessageHandler, PlaygroundLiveViewSafeAreaContainer {


    private let photoImageView =  UIImageView()
    //private let textView = UITextView()
    private var vstring = String()
    private var textColor = UIColor()
    private var pdfDocument: PDFDocument!
    private var pdfUrl: URL?
    private let pdfView = PDFView()
    private var fileName: String?
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public init(fname: String) {
        self.fileName = fname
        super.init(nibName: nil, bundle: nil)
    }
    
    override public func viewDidLoad() {
        super.viewDidLoad()

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

        // PDFViewを配置
        //let pdfView = PDFView(frame: self.view.frame)
        self.view.addSubview(pdfView)
        //PDF表示用のimageビューを配置
        pdfView.isUserInteractionEnabled = true
        pdfView.translatesAutoresizingMaskIntoConstraints  = false
        pdfView.backgroundColor = UIColor { (traitCollection: UITraitCollection) -> UIColor in
            if traitCollection.userInterfaceStyle == .dark {
                return UIColor(red: 0.12, green: 0.6, blue: 0.4, alpha: 1.0) // ダークモード用の黄緑色
            } else {
                return UIColor(red: 0.239, green: 0.969, blue: 0.675, alpha: 1.0) // ライトモード用の黄緑色
            }
        }
        pdfView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 0).isActive = true
        pdfView.bottomAnchor.constraint(equalTo: liveViewSafeAreaGuide.bottomAnchor, constant: 0).isActive = true
        pdfView.leadingAnchor.constraint(equalTo: liveViewSafeAreaGuide.leadingAnchor, constant: 0).isActive = true
        pdfView.trailingAnchor.constraint(equalTo: liveViewSafeAreaGuide.trailingAnchor, constant: 0).isActive = true
        // PDFビューを設定
        pdfView.autoScales = true
        //pdfView.displaysPageBreaks = false
        pdfView.displayMode = .singlePageContinuous
        pdfView.displayDirection = .horizontal
        pdfView.usePageViewController(true)

        // PDFをロード
        if let path = Bundle.main.path(forResource: fileName, ofType: "pdf") {
            pdfUrl = URL(fileURLWithPath: path)
            print("url = \(path)")
        }
        pdfView.document = PDFDocument(url: pdfUrl!)

        
        //写真表示用のimageビューを配置
        photoImageView.frame = view.bounds
        photoImageView.image = UIImage(systemName: "photo")
        photoImageView.contentMode = .scaleAspectFit
        view.addSubview(photoImageView)
        photoImageView.isUserInteractionEnabled = true
        photoImageView.layer.cornerRadius = 10
        photoImageView.translatesAutoresizingMaskIntoConstraints  = false
        photoImageView.topAnchor.constraint(equalTo: liveViewSafeAreaGuide.topAnchor, constant: 20).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
        photoImageView.isHidden = 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
        textView.isHidden = 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.
        //pdfView.isHidden = true
        //photoImageView.isHidden = false
        //textView.isHidden = false
    }

    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.
        //pdfView.isHidden = false
        //photoImageView.isHidden = true
        //textView.isHidden = true
    }
    
    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 .data(data) = message {
            if !data.isEmpty {
                //photoImageView.image = UIImage(data: data)
                UIView.transition(with: photoImageView,
                                  duration: 0.75,
                                  options: .transitionFlipFromLeft,
                                  animations: { self.photoImageView.image = UIImage(data: data) },
                                  completion: nil)
            } else {
                //textView.text = textView.text + "dataが空です。\n"
            }
        }
        //if case let .string(text) = message {
           // textView.text = textView.text + "\(text)\n"
        //}
    }
    
    public override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        //PDF表示を小さくしすぎないようにする。
        pdfView.minScaleFactor = pdfView.scaleFactor
        //pdfView.maxScaleFactor = pdfView.scaleFactor
    }
    
}
