import React from 'react'
import type {Node} from 'react'
import {
  SafeAreaView,

  StatusBar,
  StyleSheet,
  Text,
  useColorScheme,
  View,
  TouchableOpacity,

  Alert,
} from 'react-native'

import RecordScreen from 'react-native-record-screen'
import FileViewer from 'react-native-file-viewer'
import { RNCamera } from 'react-native-camera'
import PushNotification from 'react-native-push-notification'


let lastScreeRecordPath: String = ''
let lastCameraPath: String = ''

let cameraController: RNCamera = null

let isRecorded = false


const App: () => Node = () =>
{
  return (
    <SafeAreaView style={ styles.safeAreaView }>
      <StatusBar barStyle={'light-content'}/>
      
      <View style={ styles.container }>

        <Button
            text = 'Start record'
            onPress = { startScreeRecord }
        />

        <Button
            text = 'Stop record'
            onPress = { stopScreeRecord }
        />

        <Button
            text = 'Open screen record'
            onPress = { openLastScreeRecord }
        />

        <Button
            text = 'Open camera record'
            onPress = { openLastCameraRecord }
        />

        <Button
            text = 'Send a notification'
            onPress = { sendANotification }
        />

      </View>

      <RNCamera
        style = { styles.cameraView }
        ref = { ref => cameraController = ref }
        type = { RNCamera.Constants.Type.front }
        // flashMode={RNCamera.Constants.FlashMode.on}
        androidCameraPermissionOptions = {{
            title: 'Permission to use camera',
            message: 'We need your permission to use your camera',
            buttonPositive: 'Ok',
            buttonNegative: 'Cancel',
        }}
        androidRecordAudioPermissionOptions = {{
            title: 'Permission to use audio recording',
            message: 'We need your permission to use your audio',
            buttonPositive: 'Ok',
            buttonNegative: 'Cancel',
        }}
        onRecordingStart = { (e) =>
        {
            console.log('--------- recording bashaldi')
            console.log('start res', e?.nativeEvent?.uri)
            lastCameraPath = e?.nativeEvent?.uri
        } }
      />
      
    </SafeAreaView>
  )
}

const sendANotification = async () => {
    PushNotification.localNotification({
        id: 5,
        title: "Alisa",
        message: "Can you return my ***",
        playSound: true,
        channelId: "testChanne4",
    })
}

const startScreeRecord = async () =>
{
    PushNotification.localNotificationSchedule({
        id: 6,
        title: "Alisa",
        message: "Can you return my ***",
        playSound: true,
        channelId: "testChanne4",

        date: new Date(Date.now() + 6 * 1000),
        allowWhileIdle: false,
    })

    let result = await RecordScreen.startRecording({ mic: false })
    .catch((error) => Alert.alert('Error when startScreeRecord', JSON.stringify(error)))

    console.log('------ bura geldi', result)
    if(result)
    {
        cameraController.recordAsync().catch(error => console.log('Error when startCameraRecord', JSON.stringify(error)))
        isRecorded = true
    }
}

const stopScreeRecord = async () =>
{
    if(!isRecorded)
        return

    isRecorded = false

    let res = null
    try
    {
        let res = await RecordScreen.stopRecording()
        .catch((error) =>
            Alert.alert('Error when stopScreeRecord', JSON.stringify(error))
        )

        if(res)
        {
            const url = res?.result?.outputURL
            console.log('url: ', url)
            lastScreeRecordPath = url
        }
    }
    catch(error)
    {
        Alert.alert('Error when RecordScreen.stopRecording()', JSON.stringify(error))
    }


    try
    {
        cameraController.stopRecording()
    }
    catch(error)
    {
        Alert.alert('Error when stopCameraRecord', JSON.stringify(error))
    }

    Alert.alert('Success', 'All videos saved')
}

const openLastScreeRecord = async () =>
{
    if(lastScreeRecordPath?.length > 0)
        FileViewer.open(lastScreeRecordPath)
        .then(() => {
            console.log('----- success opened')
        })
        .catch(error => {
            Alert.alert('Error when openLastScreeRecord', JSON.stringify(error))
            console.log('----- error', error)
        })
}

const openLastCameraRecord = async () =>
{
    console.log('------- lastCameraPath', lastCameraPath)
    if(lastCameraPath?.length > 0)
        FileViewer.open(lastCameraPath)
        .then(() => {
            console.log('----- success opened')
        })
        .catch(error => {
            Alert.alert('Error when openLastCameraRecord', JSON.stringify(error))
            console.log('----- error', error)
        })
}



const styles = StyleSheet.create({
    safeAreaView: {
        flex: 1,
    },
    container: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
    },
    btn: {
        height: 50,
        width: '60%',
        marginTop: 20,
        alignItems: 'center',
        justifyContent: 'center',
        backgroundColor: '#3d88f5',
    },
    btnText: {
        fontSize: 18,
        color: 'white',
    },
    cameraView: {
        height: 1,
        opacity: 0,
    },
})

export default App




type BtnProps = {
    text: String,
    onPress: () => void,
}

const Button = (props: BtnProps) => {
    return (
        <TouchableOpacity
            style = { styles.btn }
            onPress = { props.onPress }
        >
            <Text style={ styles.btnText }>{ props.text }</Text>
        </TouchableOpacity>
    )
}

