import React, { Component } from 'react'
import { View, StyleSheet, Alert, } from 'react-native'
import { StackNavigationProp, } from '@react-navigation/stack'
import { RNCamera, TakePictureOptions, TakePictureResponse, } from 'react-native-camera'
import FileViewer from 'react-native-file-viewer'
import PushNotification from 'react-native-push-notification'
import RecordScreen from 'react-native-record-screen'
import Sound from 'react-native-sound'
import { format, parse, addSeconds, isThisHour, } from 'date-fns'
import { NotificationMobM, PrankTypeMobE, } from '../../models/mobileModels'
import c from '../../color/colors'
import t from '../../translator/translator'

import BasePage from '../BasePage'
import HeaderView from './HeaderView'
import BodyView from './BodyView'
import VoiceView from './VoiceView'
import BottomView from './BottomView'



type Props = {
    navigation: StackNavigationProp<''>,
    route: {
        params: {
            voice: { name: String, timeText: String, url: NodeRequire },
        },
    },
}


export default class VoicePrankCameraPage extends BasePage<Props>
{
    cameraView: RNCamera = null
    videoUrl: String = null
    voice: { name: String, timeText: String, url: NodeRequire } = null
    soundControlObj: Sound

    isCameraInProgress: Boolean = false
    isTakePhotoPressed: Boolean = false
    videoTimerInterval: Number = -1
    isStartedVideoTimer: Boolean = false
    

    state: {
        cameraType: String,
        flashMode: any,
        isPrankStarted: Boolean,
        videoTimer: Date,

        isSoundPlaying: Boolean,
    }


    constructor(props: Props)
    {
        super(props)
        this.onPressPlayPauseSound = this.onPressPlayPauseSound.bind(this)
        this.onPressStopSound = this.onPressStopSound.bind(this)
        this.onPressTakePhoto = this.onPressTakePhoto.bind(this)
        this.onPressPauseResume = this.onPressPauseResume.bind(this)
        this.startPrank = this.startPrank.bind(this)
        this.endPrank = this.endPrank.bind(this)

        this.voice = this.props.route.params?.voice

        this.state = {
            cameraType: RNCamera.Constants.Type.back,
            flashMode: RNCamera.Constants.FlashMode.off,
            isPrankStarted: false,
            videoTimer: parse('00:00:00', 'HH:mm:ss', new Date()),

            isSoundPlaying: false,
        }
    }

    componentDidMount()
    {
        this.soundControlObj = new Sound(this.voice.url)
    }

    componentWillUnmount()
    {
        this.onPressStopSound()
        this.timerStop()
    }


    render()
    {
        return (
            <>
            <View style={ styles.container }>
                <RNCamera
                    ref = { ref => this.cameraView = ref }
                    style = { styles.camera }
                    type = { this.state.cameraType }
                    flashMode = { this.state.flashMode }
                    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 = { this.startPrank }
                >

                    <HeaderView
                        secondsText = { format(this.state.videoTimer, 'mm:ss') }
                        onPressBack = { this.props.navigation.goBack }
                        isFlashTorched = { this.state.flashMode == RNCamera.Constants.FlashMode.torch }
                    />

                    <BodyView/>

                    {/* <VoiceView
                        isSoundPlaying = { this.state.isSoundPlaying }
                        onPressPlayPause = { this.onPressPlayPauseSound }
                        onPressReset = { this.onPressStopSound }
                    /> */}

                    <BottomView
                        isRecording = { this.state.isPrankStarted }
                        onPressTakePhoto = { this.onPressTakePhoto }
                        onPressPauseResume = { this.onPressPauseResume }
                    />

                </RNCamera>
            </View>
            </>
        )
    }


    onPressPlayPauseSound()
    {
        if(this.state.isSoundPlaying)
        {
            this.soundControlObj.pause()
            this.setState({ isSoundPlaying: false })
        }
        else
        {
            this.soundControlObj.play(() => this.setState({ isSoundPlaying: false }))
            this.setState({ isSoundPlaying: true })
        }
    }

    onPressStopSound()
    {
        this.soundControlObj.stop()
        this.soundControlObj.setCurrentTime(0)
        this.setState({ isSoundPlaying: false })
    }


    onPressTakePhoto()
    {
        if(this.isTakePhotoPressed)
            return
        this.isTakePhotoPressed = true

        if(!this.state.isPrankStarted)
        {
            this.cameraView.recordAsync({ codec: 'JPEG',  })
            setTimeout(this.onPressPlayPauseSound, 2000)
            // this.startPrank()
        }
        else
            this.endPrank()

        this.isTakePhotoPressed = false
    }

    onPressPauseResume()
    {
        if(this.state.isPrankStarted == false)
            return

        if(this.isStartedVideoTimer == false)
        {
            this.timerStart()
            this.isStartedVideoTimer = true
        }
        else
        {
            this.timerStop()
            this.isStartedVideoTimer = false
        }
    }


    async startPrank({ nativeEvent })
    {
        try
        {
            this.videoUrl = nativeEvent.uri
            this.setState({ isPrankStarted: true }, this.onPressPauseResume)
        }
        catch(error)
        {
            Alert.alert('Ne nachalos zapis', JSON.stringify(error))
            this.setState({ isPrankStarted: false })
        }
    }


    async endPrank()
    {
        try
        {
            this.cameraView.stopRecording()

            this.soundControlObj.pause()
            this.setState({ isSoundPlaying: false })

            if(this.videoUrl)
            {
                this.setState({ isPrankStarted: false })
                this.onPressPauseResume()

                setTimeout(
                    () =>
                    {
                        this.props.navigation.navigate('ShareVideoPage', {
                            videoPath: this.videoUrl,
                            prankType: PrankTypeMobE.VoicePrank,
                        })
                    }, 10)
            }
        }
        catch(error)
        {
            Alert.alert('Error when endPrank()', JSON.stringify(error))
        }
    }



    onPressChangeCamera()
    {
        if(this.state.cameraType == RNCamera.Constants.Type.front)
            this.setState({ cameraType: RNCamera.Constants.Type.back })
        else
            this.setState({ cameraType: RNCamera.Constants.Type.front })
    }

    onPressFlash()
    {
        if(this.state.flashMode == RNCamera.Constants.FlashMode.off)
            this.setState({ flashMode: RNCamera.Constants.FlashMode.torch })
        else
            this.setState({ flashMode: RNCamera.Constants.FlashMode.off })
    }

    timerStart()
    {
        this.videoTimerInterval = setInterval(() =>
        {
            this.state.videoTimer = addSeconds(this.state.videoTimer, 1)
            this.setState({ })
        },
        995)
    }

    timerStop()
    {
        clearInterval(this.videoTimerInterval)
    }

}



const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    camera: {
        flex: 1,
    },
})
