//=============================================================================================================================
//
// Copyright (c) 2015-2022 VisionStar Information Technology (Shanghai) Co., Ltd. All Rights Reserved.
// EasyAR is the registered trademark or trademark of VisionStar Information Technology (Shanghai) Co., Ltd in China
// and other countries for the augmented reality technology developed by VisionStar Information Technology (Shanghai) Co., Ltd.
//
//=============================================================================================================================

import GLKit
import EasyARSwift

internal class OpenGLView : GLKView {
    private var helloAR: HelloAR = HelloAR()
    private var screenRotation: Int32 = 0
    private var initialized: Bool = false
    
    public func initialize() {
        context = EAGLContext(api: EAGLRenderingAPI.openGLES3)!
        drawableColorFormat = GLKViewDrawableColorFormat.RGBA8888
        drawableDepthFormat = GLKViewDrawableDepthFormat.format24
        drawableStencilFormat = GLKViewDrawableStencilFormat.format8
        bindDrawable()
        _ = helloAR.initialize()
        initialized = true
    }
    
    deinit {
        helloAR.dispose()
    }

    public func start() {
        if (!initialized) { return }
        CameraDevice.requestPermissions(helloAR.getScheduler(), { (status, value) in
            switch status {
            case .Denied:
                print("camera permission denied")
            case .Granted:
                _ = self.helloAR.start()
            case .Error:
                print("camera permission error")
            }
        })
    }
    
    public func stop() {
        if (!initialized) { return }
        helloAR.stop()
    }
    
    override func draw(_ rect: CGRect) {
        if (!initialized) { return }

        var scale: CGFloat
        if #available(iOS 8, *) {
            scale = UIScreen.main.nativeScale
        } else {
            scale = UIScreen.main.scale
        }

        helloAR.render(Int32(frame.size.width * scale), Int32(frame.size.height * scale), screenRotation)
    }
    
    public func setOrientation(_ orientation: UIInterfaceOrientation) {
        switch orientation {
        case .portrait:
            screenRotation = 0
        case .landscapeRight:
            screenRotation = 90
        case .portraitUpsideDown:
            screenRotation = 180
        case .landscapeLeft:
            screenRotation = 270
        default:
            break
        }
    }
}
