//
//  LoginTypeSelectView.swift
//  forShip
//
//  Created by Mamoru Sugita on 2023/10/13.
//

import SwiftUI
import AVFoundation

struct LoginTypeSelectView: View{
    @Binding var isQrRead: Bool
    @Binding var viewMode: LoginViewMode
    @State var isCameraAlert = false

    var body: some View{
        VStack (spacing: 20) {
            Button(action: {
                checkCamera()
            }, label: {
                Text("Read the QR code")
                    .font(FontStyle.TitleS.font)
                    .frame(maxWidth: .infinity)
                    .frame(height: 60)
                    .foregroundColor(ColorSet.ButtonText.color)
                    .background(ColorSet.LoginBk01.color)
            })
            
            Button(action: {
                print("change mode")
                viewMode = .InputIdPassword
            }, label: {
                Text("Enter Ship ID / Password")
                    .underline()
                    .font(FontStyle.SupplementText.font)
                    .foregroundColor(ColorSet.Body.color)
            })

            .alert("Error", isPresented: $isCameraAlert) {
                Button("Cancel") {}
                Button("Setting") {
                    guard let settingsURL = URL(string: UIApplication.openSettingsURLString) else {
                        return
                    }
                    UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil)
                }
            } message: {
                Text("Please allow access to the camera in iOS settings.")
            }
        }
        .padding(.horizontal, 50)
    }

    /**
     * カメラ許可確認
     */
    func checkCamera() {
        isQrRead = true
        let status = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)

        if status == AVAuthorizationStatus.authorized {
            print(debug: "Camera permission")
        } else if status == AVAuthorizationStatus.notDetermined {
            print(debug: "Haven't asked for camera access permission yet")
        } else if status == AVAuthorizationStatus.denied {
            print(debug: "Camera not allowed")
            AVCaptureDevice.requestAccess(for: .video, completionHandler: { granted in
                if (granted == false) {
                    isCameraAlert = true
                    isQrRead = false
                }
            })
        }
    }
}

#Preview {
    LoginTypeSelectView(isQrRead: .constant(false), viewMode: .constant(.SelectType))
}
