import React, { Component } from 'react'
import { View, ScrollView, StyleSheet, BackHandler, Linking, Alert, Platform, } from 'react-native'
import { StackNavigationProp, } from '@react-navigation/stack'
import { format, } from 'date-fns'
import Video from 'react-native-video'
import RNFS from 'react-native-fs'
import Share from 'react-native-share'
import { BlurView, } from '@react-native-community/blur'
import { PrankTypeMobE, } from '../../models/mobileModels'
import { StorageService, } from '../../others'
import c from '../../color/colors'
import t from '../../translator/translator'

import BasePurePage from '../BasePurePage'
import MainPageViewer from '../../components/pageViewers/MainPageViewer'
import TransparentHeaderView from '../../components/headers/TransparentHeaderView'
import { store } from '../../redux/store'
import { LoadingGlobalModalAC, } from '../../redux/actionCreators'
import VideoInfoView from './VideoInfoView'
import ShareBtnsView from './ShareBtnsView'

// import WatermarkImage from '../../../assets/images/watermark/white_watermark.png'


type Props = {
    navigation: StackNavigationProp<''>,
    route: {
        params: {
            videoPath: String,
            prankType: PrankTypeMobE,
            isMyVideosPage: Boolean,
        },
    },
}

// const screenUrl = 'file:///data/user/0/com.umora/cache/Camera/8d9a7f63-bbbf-4329-bf21-64f11f20b963.mp4'
// const screenUrl = '/storage/emulated/0/Android/data/com.umora/files/ReactNativeRecordScreen/HD2021-06-22-01-33-04.mp4'
const screenUrl = 'file:///data/user/0/com.umora/cache/Voice_prank_2021-07-08_07_29_37.mp4'

export default class ShareVideoPage extends BasePurePage<Props>
{
    refVideoView: Video = null
    videoPath: String
    prankType: PrankTypeMobE
    isMyVideosPage: Boolean

    isDownloadPressed: Boolean = false

    state: {
        isBackVideoPaused: Boolean,
    }

    constructor(props: Props)
    {
        super(props)
        this.onPressInst = this.onPressInst.bind(this)
        this.onPressFb = this.onPressFb.bind(this)
        this.onPressTikTok = this.onPressTikTok.bind(this)
        this.onPressMore = this.onPressMore.bind(this)
        this.onPressDownload = this.onPressDownload.bind(this)

        this.isMyVideosPage = this.props.route.params?.isMyVideosPage

        if(this.isMyVideosPage)
            this.fromMyVideosInit()
        else
            this.newViewInit()

        this.state = { 
            isBackVideoPaused: false,
        }
    }

    async newViewInit()
    {
        this.prankType = this.props.route.params?.prankType || PrankTypeMobE.NoType
        this.videoPath = this.props.route.params?.videoPath || screenUrl
        if(!this.videoPath.includes('file://'))
            this.videoPath = 'file://' + this.videoPath

        // let splitedCachePath = this.videoPath.split('/')
        // let oldFileName = splitedCachePath[splitedCachePath.length - 1]
        // let splitedFileName = oldFileName.split('.')

        // let fileExtension = splitedFileName[splitedFileName.length - 1]
        // let newFileName = (this.prankType == PrankTypeMobE.VoicePrank ? 'Voice_prank_' : 'Notification_prank_') + format(new Date(), 'yyyy-MM-dd_HH_mm_ss') + `.${fileExtension}`

        // let destPath = 'file://' + RNFS.CachesDirectoryPath + '/' + newFileName

        // await RNFS.moveFile(this.videoPath, destPath)
        // console.log('------ destPath', destPath)

        // this.videoPath = destPath

        this.forceUpdate()
    }

    fromMyVideosInit()
    {
        this.prankType = this.props.route.params?.prankType || PrankTypeMobE.NoType
        this.videoPath = this.props.route.params?.videoPath || screenUrl
        if(!this.videoPath.includes('file://'))
            this.videoPath = 'file://' + this.videoPath
    }

    backAction = () =>
    {
        Alert.alert(
            t().Warning,
            t().AreYouSureYouWantToPerformThisAction,
            [
              {
                text: t().Cancel,
                style: 'cancel',
              },
              {
                text: t().Yes,
                onPress: () => this.props.navigation.popToTop(),
              },
            ],
            {
              cancelable: false,
            }
        )

        return true
    }

    componentDidMount()
    {
        console.log('----- video url', this.videoPath)
        BackHandler.addEventListener('hardwareBackPress', this.backAction)
    }

    componentWillUnmount()
    {
        BackHandler.removeEventListener('hardwareBackPress', this.backAction)
    }


    render()
    {
        return (
            <MainPageViewer>
                <TransparentHeaderView
                    title = { t().Share_this_video() }
                    onPressBack = { () => this.backAction() }
                />

                <View style={ styles.container }>

                    <VideoInfoView
                        imagePath = { this.imagePath }
                        videoPath = { this.videoPath }
                        onPressRemoveWaterMark = { null }
                    />

                    <ShareBtnsView
                        onPressInst = { this.onPressInst }
                        onPressFb = { this.onPressFb }
                        onPressTikTok = { this.onPressTikTok }
                        onPressMore = { this.onPressMore }
                        isShowDownloadBtn = { !this.isMyVideosPage }
                        onPressDownload = { this.onPressDownload }
                    />

                </View>
                <View style = { styles.backgroundView }>
                    <Video
                        style = { styles.backgroundImg }
                        source = { { uri: this.videoPath } }
                        ref = { ref => this.refVideoView = ref }
                        muted = { true }
                        paused = { true }
                        poster = { this.videoPath }
                        posterResizeMode = 'cover'
                    />
                    <BlurView
                        style = { styles.backgroundBlur }
                        blurType = 'dark'
                        blurAmount = { 5 }
                    />
                </View>
            </MainPageViewer>
        )
    }



    async onPressFb()
    {
        if(Platform.OS == 'android')
        {
            let isInstalled = await Share.isPackageInstalled('com.facebook.katana')
            if(!isInstalled.isInstalled)
            {
                Alert.alert(t().Warning, t().This_application_is_not_installed())
                return
            }
        }

        let shareFunk = Platform.select({
            android: () => Share.shareSingle({
                title: 'Umora prank',
                url: this.videoPath,
                social: Share.Social.FACEBOOK,
            }),
            ios: () => Share.open({
                title: 'Umora prank',
                url: this.videoPath,
                social: Share.Social.FACEBOOK,
                type: 'url',
            })
        })
        shareFunk && shareFunk()
    }

    async onPressInst()
    {
        if(Platform.OS == 'android')
        {
            let isInstalled = await Share.isPackageInstalled('com.instagram.android')
            if(!isInstalled.isInstalled)
            {
                Alert.alert(t().Warning, t().This_application_is_not_installed())
                return
            }
        }

        let shareFunk = Platform.select({
            android: () => Share.shareSingle({
                title: 'Umora prank',
                url: this.videoPath,
                social: Share.Social.INSTAGRAM,
            }),
            ios: () => Share.open({
                title: 'Umora prank',
                url: this.videoPath,
                social: Share.Social.INSTAGRAM,
                type: 'url',
            })
        })
        shareFunk && shareFunk()
    }

    async onPressTikTok()
    {
        let isInstalled = await Share.isPackageInstalled('com.zhiliaoapp.musically')
        if(!isInstalled.isInstalled)
        {
            Alert.alert(t().Warning, t().This_application_is_not_installed())
            return
        }
        Linking.openURL('tiktok://open')
        // Share.shareSingle({
        //     title: 'Umora prank',
        //     url: this.videoPath,
        //     social: 'TikTok',
        // })
    }

    onPressMore()
    {
        Share.open({
            title: 'Umora prank',
            url: this.videoPath,
        })
    }

    async onPressDownload()
    {
        if(this.isDownloadPressed)
            return
        this.isDownloadPressed = true

        store.dispatch(LoadingGlobalModalAC.toggleVisibility(true))

        try
        {
            console.log('--- video path', this.videoPath)

            let splitedCachePath = this.videoPath.split('/')
            let fileName = splitedCachePath[splitedCachePath.length - 1]
            let splitedFileName = fileName.split('.')
            console.log('--- splitedFileName', splitedFileName)

            let fileExtension = splitedFileName[splitedFileName.length - 1]
            fileName = (this.prankType == PrankTypeMobE.VoicePrank ? 'Voice_prank_' : 'Notification_prank_') + format(new Date(), 'yyyy-MM-dd_HH_mm_ss') + `.${fileExtension}`

            let destPath = Platform.select({
                android: 'file://' + RNFS.DownloadDirectoryPath + '/' + fileName,
                ios: 'file://' + RNFS.LibraryDirectoryPath + '/' + fileName
            })

            console.log('----- destPath', destPath)

            await RNFS.moveFile(this.videoPath, destPath)
            this.props.navigation.popToTop()
            // FileViewer.open(destPath)

            let allVideos = await StorageService.getMyVideos() || []
            allVideos.push({
                uid: fileName,
                name: fileName,
                createDate: new Date(),
                path: destPath,
                prankType: this.prankType,
            })
            StorageService.saveMyVideos(allVideos)

            Alert.alert(t().Message, t().Saved())
        }
        finally
        {
            this.isDownloadPressed = false
            store.dispatch(LoadingGlobalModalAC.toggleVisibility(false))
        }
    }

}



const styles = StyleSheet.create({
    container: {
        flex: 1,
        paddingHorizontal: 40,
        // backgroundColor: c().main_black,
        // backgroundColor: c().main_white,
    },
    backgroundView: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
        backgroundColor: c().main_black,
        zIndex: -1,
    },
    backgroundImg: {
        flex: 1,
    },
    backgroundBlur: {
        position: 'absolute',
        top: 0,
        left: 0,
        right: 0,
        bottom: 0,
    },
})

const waterMarkUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/33/Vanamo_Logo.png'
