import 'react-native-gesture-handler';
import * as React from 'react';
import { PokktExtension } from './PokktAds';//Step 1
import AdPlayerScreen from './AdPlayerScreen';
import {
SafeAreaView,
Platform,
Button,
View,
ScrollView,
Text,
StyleSheet,
TextInput,
Switch,
NativeModules
} from 'react-native';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
//import { createStackNavigator } from 'react-navigation'; // Version can be specified in package.json
import { DeviceEventEmitter,NativeEventEmitter } from 'react-native';

var pe = window.plugins.pokktExtension; //Step 2
var emitter;//Step 3 -- needed for ios
class HomeScreen extends React.Component {
	static navigationOptions = {
    	title: "POKKT"
  	}
	constructor(props) {
    	super(props);
    	this.state = {
      		appId: 'f303768353fb89d188f24b36c4d80b2e',
      		secKey: 'f3b2bec2234694467398589e1606234b',
      		version: '0.0'
		};
		//set version number
  		pe.getSDKVersion((ver) => {
  			console.log('Version : ',ver);
  			this.setState({version: ver})
  		})
  		//set debug
        pe.setDebug("true");
	}

	render() {
	return (
		<SafeAreaView>

	<ScrollView>
	<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
		<Text style={{padding: 5, fontSize: 14}}>
    		{this.state.version}
    	</Text>
    	<Text style={{padding: 5, fontSize: 14}}>
    		Application Id
    	</Text>
    	<TextInput
			accessibilityLabel="edt_application_id"
			testID="edt_application_id"
        	style={{padding: 5,fontSize: 14, height: 30, width:250}}
        	onChangeText = {(text) => {this.setState({ appId: text })}}
        	placeholder= 'f303768353fb89d188f24b36c4d80b2e'
    	/>

    	<Text style={{padding: 5, fontSize: 14}}>
        	Security Key
    	</Text>
		<TextInput
			accessibilityLabel="edt_security_key"
			testID="edt_security_key"
			style={{padding: 5,fontSize: 14, height: 30, width:250}}
    		onChangeText = {(text) => {this.setState({ secKey: text })}}
          	placeholder="f3b2bec2234694467398589e1606234b"
    	/>

    	<View style={styles.buttonContainer}>
    		<Button
          		title="Set Pokkt Config"
          		onPress= {() => {
          		pe.setPokktConfig(this.state.appId,this.state.secKey );
          		pe.setDataAccessConsent(false,true );
          		pe.setThirdPartyUserId("12345");
          		var adPlayerViewConfig = pe.createAdPlayerViewConfig();
				// set properties values to adPlayerViewConfig 
				pe.setAdPlayerViewConfig(JSON.stringify(adPlayerViewConfig));

          		this.props.navigation.navigate('Ads')}
          		}
        	/>
    	</View>
    </View>
    </ScrollView>
	</SafeAreaView>
    );
  }
}

//=============================================================================Ads Screen
class AdsScreen extends React.Component {
	static navigationOptions = {
    	title: "Ad Type"
  	}
	render() {
    return (
		<SafeAreaView>

    <ScrollView>
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop:30 }}>
    	<View style={styles.buttonContainer}>
    		<Button
          		title="FullScreen Ads"
          		onPress={() => this.props.navigation.navigate('FullScreenAds')}
          	/>
    	</View>
    	<View style={{height: 30, backgroundColor: 'powderblue'}} />
    	<View style={styles.buttonContainer}>
        	<Button
         		title="Banner"
          		onPress={() => this.props.navigation.navigate('Banner')}
        	/>
    	</View>
		<View style={{height: 30, backgroundColor: 'powderblue'}} />
    	<View style={styles.buttonContainer}>
        	<Button
         		title="More"
          		onPress={() => this.props.navigation.navigate('More')}
        	/>
    	</View>
    </View>
    </ScrollView>
	</SafeAreaView>
    );
  }
}
//========================================================================FullScreen Ads Screen
class FullScreenAds extends React.Component {
	static navigationOptions = {
    	title: "FullScreen Ads",
  	}
	constructor(props) {
    	super(props);
    	this.state = {
      		screenId: 'Enter Screen Id',
      		message : ''
		};
		this.adCachingResultCallback = this.adCachingResultCallback.bind(this);
		this.adDisplayedResultCallback = this.adDisplayedResultCallback.bind(this);
		this.adClickedCallback = this.adClickedCallback.bind(this);
		this.adClosedCallback = this.adClosedCallback.bind(this);
		this.adGratifiedCallback = this.adGratifiedCallback.bind(this);

	}
	//Constructor end
	adCachingResultCallback(param) {
			var data = JSON.parse(param);
			if(data.ERROR_MESSAGE!= null && data.ERROR_MESSAGE.length == 0) {
				this.setState({message:'AdCachingCompleted'});
				console.log('AdCachingCompleted '+param);
			} else {
				this.setState({message:'AdCachingFailed'});
  				console.log('AdCachingFailed '+param);
			}
  	}
  	adDisplayedResultCallback(param) {
		var data = JSON.parse(param);
		if(data.ERROR_MESSAGE!= null && data.ERROR_MESSAGE.length == 0) {
	    	this.setState({message:'AdDisplayed'});
			console.log('AdDisplayed '+param);
		} else {
			this.setState({message:'AdFailedToShow'});
			console.log('AdFailedToShow '+param);
		}
  	}
	adClickedCallback(param) {
		this.setState({message:'AdClicked'});
		console.log('AdClicked '+param);
	}
  	adCompletedCallback(param) {
	    	this.setState({message:'AdCompleted'});
  			console.log('oAdCompleted '+param);
  	}
  	adClosedCallback(param) {
		var data = JSON.parse(param);
		if(data.AD_COMPLETED) {
  			console.log('AdCompleted '+param);
	    	this.setState({message:'AdClosed'});
			console.log('AdClosed '+param);
		} else {
			this.setState({message:'AdSkipped'});
			console.log('AdSkipped '+param);
		}
	  }
	adGratifiedCallback(param) {
		var data = JSON.parse(param);
		if(data.REWARD > 0) {
			pe.showToast("Points earned : " + data.REWARD);
			  console.log('AdGratified '+param);
		}
  	}
  	
	  componentDidMount() {
		/*DeviceEventEmitter.addListener('VideoAdCachingFailed', (param) => {
	    	this.setState({message:'VideoAdCachingFailed'});
  			console.log('VideoAdCachingFailed '+param);
  		});*/
  		const { PokktPluginEvent } = NativeModules;
  		emitter = Platform.select({ios: new NativeEventEmitter(PokktPluginEvent),
 					android: DeviceEventEmitter});
	    emitter.addListener('AdCachingResult', this.adCachingResultCallback);
  		emitter.addListener('AdDisplayedResult', this.adDisplayedResultCallback);
		emitter.addListener('AdClicked', this.adClickedCallback);
		emitter.addListener('AdClosed', this.adClosedCallback);
		emitter.addListener('AdGratified', this.adGratifiedCallback);

	}
	componentWillUnmount() {
		console.log("unmount");
	    emitter.removeListener('AdCachingResult', this.adCachingResultCallback);
  		emitter.removeListener('AdDisplayedResult', this.adDisplayedResultCallback);
		emitter.removeListener('AdClicked', this.adClickedCallback);
		emitter.removeListener('AdClosed', this.adClosedCallback);
		emitter.removeListener('AdGratified', this.adGratifiedCallback);

	}

	render() {
    return (
		<SafeAreaView>

    <ScrollView>
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      	<Text style={{padding: 10, fontSize: 14}}>
        	{this.state.message}
	  	</Text>
      	<Text style={{padding: 10, fontSize: 14}}>
        	Screen Id
	  	</Text>
      	<TextInput style={{height: 40, width:250 ,justifyContent: 'center'}}
    		onChangeText = {(text) => {this.setState({ screenId: text })}}
          	placeholder="Enter Screen Id"
    	/>
      	<View style={styles.buttonContainer}>
        	<Button
          		title="Cache Ad"
          		onPress= {() => {
					this.setState({message:''});
					pe.cacheAd(this.state.screenId);}}
        	/>
        </View>
        <View style={{height: 10, backgroundColor: 'powderblue'}} />
        <View style={styles.buttonContainer}>
        	<Button
          		title="Show Ad"
          		onPress= {() => {
          					pe.isAdCached(this.state.screenId, (result) => {
          						Platform.select({ios: console.log("Ad is Cached : " + result),
 												android: pe.showToast("Ad is Cached : " + result)});
							  });
							this.setState({message:''});
        					pe.showAd(this.state.screenId);
          				  }
          			}
        	/>
        </View>
      </View>
      </ScrollView>
	  </SafeAreaView>
    );
  }
}
//============================================================================Banner
class BannerScreen extends React.Component {
	static navigationOptions = {
    	title: "Banner"
  	}
	constructor(props) {
    	super(props);
    	this.state = {
			screenId: 'Enter Screen Id',
      		message : ''
		};
		this.bannerLoadedCallback = this.bannerLoadedCallback.bind(this);
		this.bannerClickedCallback = this.bannerClickedCallback.bind(this);
	}
	bannerLoadedCallback(param) {
		var data = JSON.parse(param);
		if(data.ERROR_MESSAGE!= null && data.ERROR_MESSAGE.length == 0) {
			this.setState({message:'BannerLoaded'});
			console.log('BannerLoaded '+param);
		} else {
			this.setState({message:'BannerLoadFailed'});
			console.log('BannerLoadFailed '+param);
		}
	}
	bannerClickedCallback(param) {
			this.setState({message:'BannerClicked'});
		  	console.log('BannerClicked '+param);
  	}
	  componentDidMount() {
		const { PokktPluginEvent } = NativeModules;
  		emitter = Platform.select({ios: new NativeEventEmitter(PokktPluginEvent),
 					android: DeviceEventEmitter});
		emitter.addListener('AdDisplayedResult', this.bannerLoadedCallback);
		emitter.addListener('AdClicked', this.bannerClickedCallback);
	}
	componentWillUnmount() {
		console.log("unmount");
		emitter.removeListener('AdDisplayedResult', this.bannerLoadedCallback);
		emitter.removeListener('AdClicked', this.bannerClickedCallback);
  		pe.destroyBanner(this.state.screenId);
	}
	render() {
    return (
		<SafeAreaView>

    <ScrollView>
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      	<Text style={{padding: 10, fontSize: 14}}>
        	{this.state.message}
	  	</Text>
      	<Text style={{padding: 10, fontSize: 14}}>
        	Screen Id
	  	</Text>
      	<TextInput style={{height: 40, width:250 ,justifyContent: 'center'}}
    		onChangeText = {(text) => {this.setState({ screenId: text })}}
          	placeholder="Enter Screen Id"
    	/>
      	<View style={styles.buttonContainer}>
        	<Button
          		title="Show Banner"
          		onPress= {() => {pe.showAd(this.state.screenId,8);}}
        	/>
        </View>
        <View style={{height: 10, backgroundColor: 'powderblue'}} />
        <View style={styles.buttonContainer}>
        	<Button
          		title="Destroy Banner"//handle back button. destroy banner and remove listener also
				  onPress= {() => {
					pe.destroyBanner(this.state.screenId);
					this.setState({message:''});}}
        	/>
        </View>
      </View>
      </ScrollView>
	  </SafeAreaView>
    );
  }
}

//=============================================================================More Screen
class MoreScreen extends React.Component {
	static navigationOptions = {
    	title: "Setting"
  	}
	render() {
    return (
		<SafeAreaView>

    <ScrollView>
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', paddingTop:30 }}>
    	<View style={styles.buttonContainer}>
    		<Button
          		title="AdPlayer View Config"
          		onPress={() => this.props.navigation.navigate('AdPlayer')}
          	/>
    	</View>
    </View>
    </ScrollView>
	</SafeAreaView>
    );
  }
}

const Stack = createStackNavigator();
function App() {
	return (
	  <NavigationContainer>
		<Stack.Navigator initialRouteName="Home">
		  <Stack.Screen name="Home" component={HomeScreen} />
		  <Stack.Screen name="Ads" component={AdsScreen} />
		  <Stack.Screen name="FullScreenAds" component={FullScreenAds} />
		  <Stack.Screen name="Banner" component={BannerScreen} />
		  <Stack.Screen name="More" component={MoreScreen} />
		  <Stack.Screen name="AdPlayer" component={AdPlayerScreen} />
		</Stack.Navigator>
	  </NavigationContainer>
	);
}
export default App;

const styles = StyleSheet.create({
  buttonContainer: {
    width : 250,
    borderRadius: 10,
    padding: 5,
    shadowColor: '#000000',
    shadowOffset: {
      width: 0,
      height: 3
    },
    shadowRadius: 10,
	shadowOpacity: 0.25,
	justifyContent:'center',
	alignSelf:'center'
  },
});