// plug in
import React, { Component } from "react";
import {
  Platform,
  StyleSheet,
  View,
  SafeAreaView,
  TouchableOpacity,
  ImageBackground,
  NetInfo,
  Alert,
  StatusBar,
  Keyboard,
  TouchableWithoutFeedback,
  AppState,
  BackHandler
} from "react-native";
import { observable, transaction } from "mobx";
import Text from "react-native-text";
import { observer, inject } from "mobx-react/native";
import Icon from "react-native-vector-icons/dist/Ionicons";
import Icon2 from "react-native-vector-icons/dist/MaterialCommunityIcons";
import { SearchBar } from "react-native-elements";
import { scale, verticalScale, moderateScale } from "react-native-size-matters";
import debounce from "lodash.debounce";
import Toast, { DURATION } from "react-native-easy-toast";
import PopupDialog, { SlideAnimation } from "react-native-popup-dialog";
import firebase from "react-native-firebase";
import Autocomplete from "react-native-autocomplete-input";
import { ifIphoneX } from 'react-native-iphone-x-helper'
// component
import TopMessageText from "../../components/Menu/topMessageText";
import MenuFlatList from "../../components/Menu/menuFlatList";
import TotalPriceView from "../../components/Menu/totalPriceView";
import MenuDetailsView from "../../components/Menu/menuDetailsView";
import GoogleAutoComplete from "../../components/Menu/googleAutoComplete";
import Map from "../../components/Menu/map";
// function
import AsyncStorageHelper from "../../config/asyncStorageHelper";
import Log from '../../config/log'
import Size from "../../config/size";
import { width, height } from "../../config/screen";
import api from "../../stores/api";
import theme from "../../config/colors";
import MyStatusBar from "../../components/Public/statusBar";
import Language from "../../config/language"
import language from "../../config/language";
const log = new Log()
const size = new Size();
const asyncStorageHelper = new AsyncStorageHelper();

const slideAnimation = new SlideAnimation({
  slideFrom: "bottom"
});
const endDate = new Date();
endDate.setHours(endDate.getHours() + 1);

@inject(["menuStore"], ["userStore"])
@observer
export default class Menu extends Component {
  data = {};
  @observable
  menuDetails = {
    id: 0,
    count: 0,
    price: 0,
    name: "",
    nameEn: "",
    imageURL: "",
    intro_ch: "",
    intro_en: "",
    restaurant: {
      name: "",
      nameEn: "",
      addrEn: "",
      addr: ""
    }
  };

  @observable
  query = "";

  @observable
  autoPlaceFocus = false;

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

  static navigationOptions = {
    drawerLabel: "Menu of the Day",
    swipeEnabled: false,
    tabBarLabel: language.en.menu,
  };


  async componentDidMount() {
    this.checkPermission();
  
   // this.createNotificationListeners();
    
  }
  

  async checkPermission() {
    const enabled = await firebase.messaging().hasPermission();
    if (enabled) {
      this.getToken();
    } else {
      this.requestPermission();
    }
  }

  onClickAction(data, details) {
   this.map.goPosition(data, details)
  }

  add(id) {
    this.store.addCount(id);
  }

  sum(id) {
    this.store.sumCount(id);
  }

  //3
  async getToken() {
    let fcmToken = await AsyncStorage.getItem("fcmToken", value);
    if (!fcmToken) {
      fcmToken = await firebase.messaging().getToken();
      if (fcmToken) {
        // user has a device token
        await AsyncStorage.setItem("fcmToken", fcmToken);
      }
    }
  }

  //2
  async requestPermission() {
    try {
      await firebase.messaging().requestPermission();
      // User has authorised
      this.getToken();
    } catch (error) {
      // User has rejected permissions
      console.log("permission rejected");
    }
  }


    componentWillMount() {
      BackHandler.addEventListener('hardwareBackPress', function () {
        return true
      })
    }
    getIndex(id) {
      var index = this.userStore.pickupPointLabel.findIndex(function(item, i) {
        return item.id == parseInt(id);
      });
  
      return index;
    }
  
    confirmAction(id) {
      Alert.alert(
        "",
        "Select " +
          this.userStore.pickupPointLabel[this.getIndex(id)].value +
          "?",
        [
          { text: "Cancel", onPress: () => console.log("Cancel") },
          { text: "Yes", onPress: () => this.update(id) }
        ]
      );
    }

  componentDidMount(){

    
    // console.log('token: '+ this.userStore.userData.data.token)
       //this.store.userCoupon(this,this.userStore.userData.data.token,true)

    AppState.addEventListener('change', (state) => {
       if (state === 'active') {
        console.log('state active');
        this.store.updateMenu()
       } 
      if(state === 'background'){               
       console.log('background');
      }
    })
    this.props.navigation.addListener('willFocus', (route) => {this.store.updateMenu()});
   }

  async createNotificationListeners() {
    /*
    * Triggered when a particular notification has been received in foreground
    * */
    this.notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        const { title, body } = notification;
        this.showAlert(title, body);
      });

    /*
    * If your app is in background, you can listen for when a notification is clicked / tapped / opened as follows:
    * */
    this.notificationOpenedListener = firebase
      .notifications()
      .onNotificationOpened(notificationOpen => {
        const { title, body } = notificationOpen.notification;
        this.showAlert(title, body);
      });

    /*
    * If your app is closed, you can check if it was opened by a notification being clicked / tapped / opened as follows:
    * */
    const notificationOpen = await firebase
      .notifications()
      .getInitialNotification();
    if (notificationOpen) {
      const { title, body } = notificationOpen.notification;
      this.showAlert(title, body);
    }
    /*
    * Triggered for data only payload in foreground
    * */
    this.messageListener = firebase.messaging().onMessage(message => {
      //process data message
      console.log(JSON.stringify(message));
    });
  }

  showAlert(title, body) {
    Alert.alert(
      title,
      body,
      [{ text: "OK", onPress: () => console.log("OK Pressed") }],
      { cancelable: false }
    );
  }

  navigatieAction(page, Param) {
    this.props.navigation.navigate(page, Param);
  }

  searchClear() {}

  searchChangeText() {}

  foodInformationPagePopUp() {
    
    this.popupDialog.show();
  }

  foodInformationPageDismiss() {
    this.popupDialog.dismiss();
  }

  foodInformationPageDismissedCallBack() {
    console.log("dismiss dialog");
  }

  update(id){
   // this.autoPlaceFocus = false;
   console.log('update')
   this.googleInput.blur()
   asyncStorageHelper.saveData("pickupPointId", id);
   this.store.pickupPointId = id;
   this.userStore.pickupPointId = id;
   log.firebaseLog('change_pickuppoint_from_menu',{logined:this.userStore.logined,pickupPointId:id})
    this.store.updateMenuByMap(this,id); 
    this.googleInput.onTextChange(id);
    asyncStorageHelper.getData("userInfo", userInfo => {
      if (userInfo != null) {
     this.userStore.savePickUpPointToServer(id);
      }
    });
    
  }

  render() {
    log.firebaseClass('menu')
    return (
      <SafeAreaView style={{ flex: 1, backgroundColor: theme.mainColor }}>
        
        <MyStatusBar
          backgroundColor={theme.mainColor}
          barStyle="light-content"
        />
        <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <View style={styles.container}>

          <View style={[this.autoPlaceFocus? styles.topContainerForIphoneX:styles.topContainer]} />
          
          {this.autoPlaceFocus == false ? (
           <View style={styles.titleAndDateContainer}>
           <TopMessageText date={this.store.cutoffDateTime} />
         </View>

          ) : (
           <View/>
          )}
        
          {this.autoPlaceFocus == false ? (
            <View style={styles.flatViewContainer}>
              <MenuFlatList data={this.store.menu} menu={this} />
            </View>
          ) : (
            <Map  perfdefinedPlaces = {this.userStore.perdefinedPlaces} onRef={ref => (this.map = ref)} onPress ={(id)=>{
              this.confirmAction(id)
           }}/>
          )}
          <View style={{ position: "absolute", top: verticalScale(1) }}>
            <GoogleAutoComplete
              onRef={ref => (this.googleInput = ref)}
              perdefinedPlaces={this.userStore.perdefinedPlaces}
              onFocus={() => {
                this.autoPlaceFocus = true;
              }}
              onPress = {(data,details)=>{this.onClickAction(data,details)}}
            />
          </View>
        </View>
        </TouchableWithoutFeedback>

        <PopupDialog
          ref={popupDialog => {
            this.popupDialog = popupDialog;
          }}
          dialogAnimation={slideAnimation}
          height={height - moderateScale(90)}
          onDismissed={() => this.foodInformationPageDismissedCallBack()}
        >
          <MenuDetailsView self={this} />
        </PopupDialog>
        <TotalPriceView self={this} />
        <Toast ref="toast" />
      </SafeAreaView>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "white"
  },

  topContainer: {
    height: "8%",
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: theme.mainColor
  },

  topContainerForIphoneX:{
    ...ifIphoneX({
      height: "12%",
    },
      {
        height: "8%",
    }),
    width: "100%",
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: theme.mainColor
  },


  titleAndDateContainer: {
    height: "9%",
    width: "100%",
    backgroundColor: theme.mainColor,
    justifyContent: "center"
  },

  flatViewContainer: {
    height: "85%",
    width: "100%",
    marginTop: 10,
    alignItems: "center",
  }
});
