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 { format } from 'date-fns'
import { NotificationMobM, } from '../../models/mobileModels'
import c from '../../color/colors'
import t from '../../translator/translator'

import BasePurePage from '../BasePurePage'
import HeaderView from './HeaderView'
import BodyView from './BodyView'
import BottomView from './BottomView'


type Props = {
    navigation: StackNavigationProp<''>,
    route: {
        params: {
            notifications: NotificationMobM[],
        },
    },
}


export default class NoticifationPrankCameraPage extends BasePurePage<Props>
{
    cameraView: RNCamera = null

    isCameraInProgress: Boolean = false
    isPrankStarted: Boolean = false
    sendedNotificationId = 1000
    notifications: NotificationMobM[] = []

    state: {
        cameraType: String,
        flashMode: any,
        firstImage: TakePictureResponse,
        lastImage: TakePictureResponse,
    }


    constructor(props: Props)
    {
        super(props)
        this.onPressTakePhoto = this.onPressTakePhoto.bind(this)
        this.onPressChangeCamera = this.onPressChangeCamera.bind(this)
        this.onPressFlash = this.onPressFlash.bind(this)
        this.startPrank = this.startPrank.bind(this)
        this.endPrank = this.endPrank.bind(this)

        this.notifications = this.props.route.params?.notifications

        this.state = {
            cameraType: RNCamera.Constants.Type.front,
            flashMode: RNCamera.Constants.FlashMode.off,
            firstImage: null,
            lastImage: null,
        }
    }

    componentDidMount()
    {
        // this.startPrank()
    }


    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',
                    } }
                >
                {/* <View style={ styles.camera }> */}

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

                    <BodyView/>

                    <BottomView
                        onPressTakePhoto = { this.onPressTakePhoto }
                        onPressLastImg = { this.endPrank }
                    />

                {/* </View> */}
                </RNCamera>
            </View>
            </>
        )
    }


    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 })
    }

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

        let takePicOptions: TakePictureOptions = null
        if(!this.state.firstImage)
        {
            takePicOptions = {
                pauseAfterCapture: true,
                base64: true,
            }
        }
        else
        {
            takePicOptions = {
                pauseAfterCapture: true,
                doNotSave: true,
                base64: true,
                quality: 0.1,
            }
        }

        this.cameraView.takePictureAsync(takePicOptions)
        .then(pic =>
        {
            if(!this.firstImage)
            {
                this.setState({ firstImage: pic })
            }
            else
            {
                this.setState({ lastImage: pic })
            }
        })
        .finally(() =>
        {
            this.cameraView.resumePreview()
            this.isCameraInProgress = false
        })
    }


    async startPrank()
    {
        if(this.isPrankStarted)
            return
        this.isPrankStarted = true

        try
        {
            let result = await RecordScreen.startRecording({ mic: true })

            if(result != true)
                throw 'Ne nachalos!!! ' + JSON.stringify(result)

            for (let i = 0; i < this.notifications.length; i++)
            {
                const notif = this.notifications[i]

                if(notif.senderName && notif.notificationText)
                    this.sentNotification(notif.senderName, notif.notificationText, notif.timeValue)   
            }
        }
        catch(error)
        {
            Alert.alert('Ne nachalos zapis', JSON.stringify(error))
            this.isPrankStarted = false
        }
    }


    async endPrank()
    {
        let res = null
        try
        {
            let res = await RecordScreen.stopRecording()

            if(res)
            {
                const url = res?.result?.outputURL

                this.props.navigation.navigate('ShareVideoPage', {
                    imagePath: this.state.firstImage.uri,
                    videoPath: url,
                })
            }
        }
        catch(error)
        {
            Alert.alert('Error when endPrank()', JSON.stringify(error))
        }
        finally
        {
            this.isPrankStarted = false
        }
    }


    sentNotification(title: String = '', message: String = '', delaySeconds: Number = 0)
    {
        PushNotification.localNotificationSchedule({
            id: this.sendedNotificationId++,
            title,
            message,
            playSound: true,
            channelId: 'testChanne4',
            date: new Date(Date.now() + delaySeconds * 1000),
            allowWhileIdle: true,
        })
    }

}



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