// plugin
import React, { Component } from 'react';
import Text from 'react-native-text';
import { StyleSheet, View, FlatList, TouchableOpacity, Alert } from 'react-native';
import { observer, inject } from 'mobx-react/native'
import { observable, transaction } from 'mobx';
import Icon from 'react-native-vector-icons/dist/Ionicons';
import { scale, verticalScale, moderateScale } from 'react-native-size-matters';
// function
import Size from '../../config/size';
import Log from '../../config/log'
import { width, height } from '../../config/screen';
const size = new Size;
import AsyncStorageHelper from '../../config/asyncStorageHelper'
import theme from '../../config/colors'
const log = new Log()
const asyncStorageHelper = new AsyncStorageHelper
@inject(["menuStore"], ["userStore"])
@observer
export default class TotalPriceView extends Component {

    constructor(props) {
        super(props);
        this.store = this.props.menuStore;
        this.userStore = this.props.userStore;
    }

    getIndex(id){
        var index = this.userStore.pickupPointLabel.findIndex(function(item, i){
     
         return item.id == parseInt(id)
       });
    
       return index
       
       }


    deg2rad(deg) {
        return deg * (Math.PI / 180)
    }

    getDistanceFromLatLonInKm(lat1, lon1, lat2, lon2) {
        var R = 6371; // Radius of the earth in km
        var dLat = this.deg2rad(lat2 - lat1);  // deg2rad below
        var dLon = this.deg2rad(lon2 - lon1);
        var a =
            Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
            Math.sin(dLon / 2) * Math.sin(dLon / 2)
            ;
        var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        var d = R * c; // Distance in km
        return d;
    }


    clickAction() {
        if (this.userStore.logined) {
            asyncStorageHelper.getData('pickupPointId', pickupPointId => {
                if (pickupPointId != null) {
                    if(this.userStore.addedCard ){
                    log.firebaseLog("press_order_now_button",{logined:this.userStore.logined})
                    this.userStore.pickupIndex = this.getIndex(pickupPointId)
                    this.store.getOrderedItems(this.props.self,this.userStore.userData.data.token)

                    }else{
                        Alert.alert(
                            '',
                            'Please input your credit Card info',
                            [
                                { text: 'Cancel', onPress: () => {console.log('Cancel'),log.firebaseLog('press_creditCard_info_cancel_onMenu_alert',{logined:this.userStore.logined}) }},
                                { text: 'Ok', onPress: () => {this.props.self.navigatieAction('account'),log.firebaseLog('press_creditCard_info_ok_onMenu_alert',{logined:this.userStore.logined}) }},
                            ],
    
                        )

                    }
                }
                else {

                    if (this.userStore.userLocation != null) {
                        var Param = {}
                        try {
                            this.userStore.pickupLoactionPoint.data.content.forEach(element => {
                              var km =  this.getDistanceFromLatLonInKm(element.lat,element.lng,this.userStore.userLocation.coords.latitude,this.userStore.userLocation.coords.longitude)
                              console.log(km)
                              if(km<1){
                                 Param = {'title': 'Pick the loaction'}
                              }
                            });
                        } catch (e) {
                            console.log(e)
                        
                        }
                        Alert.alert(
                            '',
                            'Please select the pickup location',
                            [
                                { text: 'Cancel', onPress: () => console.log('Cancel') },
                                { text: 'Go', onPress: () => this.props.self.navigatieAction('Location',Param) },
                            ],
    
                        )

                    }else{
                        Alert.alert(
                            '',
                            'Please select the pickup location',
                            [
                                { text: 'Cancel', onPress: () => console.log('Cancel') },
                                { text: 'Go', onPress: () => this.props.self.navigatieAction('account') },
                            ],
    
                        )
                    }
                }
            })

        } else {
            Alert.alert(
                '',
                'Please login',
                [
                    { text: 'Cancel', onPress: () => console.log('Cancel') },
                    { text: 'Login', onPress: () => this.props.self.navigatieAction('Login') },
                ],

            )
        }
    }

    render() {
        if (!this.store.selected) {
            return null
        } else {
            return (
                <View style={{
                    position: 'absolute',
                    bottom: 0,
                    width: width,
                    height: verticalScale(50),
                    flexDirection: 'row',
                    justifyContent: 'space-between',
                    alignItems: 'center',
                    backgroundColor: theme.mainColor
                }}>
                    <View style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginLeft: moderateScale(10),
                    }}>
                        <Icon name="md-close-circle" size={size.getSize(24)} color='white'
                            onPress={() => this.store.cleanAll()} />
                        <Text style={{ color: 'white', marginLeft: 10 }}>
                            HKD {this.store.totalMoney.toFixed(2)}
                        </Text>
                    </View>

                    <TouchableOpacity style={{
                        flexDirection: 'row',
                        alignItems: 'center',
                        marginRight: moderateScale(10)
                    }}
                        onPress={() => this.clickAction()}>
                        <Text style={{ color: 'white', marginRight: 10 }}>
                            ORDER NOW
                    </Text>
                        <Icon name="ios-arrow-forward" size={size.getSize(24)} color='white' />
                    </TouchableOpacity>

                </View>
            )
        }
    }
}