import { observable, action, transaction, AsyncStorage } from "mobx";
import api from "./api";
import axios from "axios";
import { Alert } from "react-native";
import AsyncStorageHelper from "../config/asyncStorageHelper";
import Toast, { DURATION } from "react-native-easy-toast";
import Permissions from "react-native-permissions";
import firebase from "react-native-firebase";
import { Notification } from "react-native-firebase";
import { Geolocation } from "react-native";
import language from "../config/language";
import Global from "../../app/Global";
import ConnectFail from "../config/connectFail";
const asyncStorageHelper = new AsyncStorageHelper();
const connectFail = new ConnectFail();
class User_store {
  @observable
  logined = false;
  @observable
  userData = {};
  @observable
  signUpData = {};
  @observable
  loading = false;
  @observable
  resend = false;
  @observable
  addedCard = false;
  @observable
  creditCardinfo = {};
  @observable
  countdown = 10;
  @observable
  pickupPointId = null;

  pickupLoactionPoint = {};
  pickupPointLabel = [];
  pickupIndex = 0;
  cardInfo = null;
  cardNumber = null;
  @observable
  userLocation = null;
  perdefinedPlaces = [];

  @observable
  isSignUp = false;
  @observable
  isSignUpVerify = false;
  @observable
  text = language.en;
  @observable
  languageSelection = "english";
  @observable
  OrderEndTime = { orderEndTime: "", orderStartTime: "" };

  notificationInit(mid) {
    firebase
      .messaging()
      .hasPermission()
      .then(enabled => {
        if (enabled) {
          firebase
            .messaging()
            .getToken()
            .then(notificationToken => {
              console.log("LOG: ", notificationToken);
              this.regUserNotificationToken(notificationToken, mid);
            });
          // user has permissions
        } else {
          firebase
            .messaging()
            .requestPermission()
            .then(() => {
             // alert("User Now Has Permission");
            })
            .catch(error => {
              console.log(error);
            //  alert("Error", error);
              // User has rejected permissions
            });
        }
      });

    this.notificationListener = firebase
      .notifications()
      .onNotification(notification => {
        // Process your notification as required
        const {
          body,
          data,
          notificationId,
          sound,
          subtitle,
          title
        } = notification;
        console.log("LOG: ", title, body, JSON.stringify(data));
      });
  }

  @action
  async regUserNotificationToken(notificationToken, mid) {
    var token = this.userData.data.token;
    var requestURL = api.regPushToken;
    var data = {
      mid: mid,
      token: notificationToken
    };
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        }
      });
      asyncStorageHelper.saveString("notificationToken", notificationToken);

      console.log(response);
    } catch (e) {
      //  this.loading = false;
      console.log(e);
    }
  }

  @action
  async regUserNotificationTokenWithNoMid(notificationToken) {
   //var token = this.userData.data.token;
    var requestURL = api.regPushToken;
    var data = {
      token: notificationToken
    };
    try {
      const response = await axios.put(requestURL, data, {
        headers: {
        //  Authorization: token,
          "Content-Type": "application/json"
        }
      });
      asyncStorageHelper.saveString("notificationToken", notificationToken);

      console.log(response);
    } catch (e) {
      //  this.loading = false;
      console.log(e);
    }
  }


  @action
  async savePickupPointToServer(pickuppointid){
    var token = this.userData.data.token;
    var id = this.userData.data.member.id;
    var requestURL = api.member+'id'+'/select_pickup_location/'+pickuppointid
    try {
      const response = await axios.post(requestURL, token);
  
     
    } catch (e) {
      console.log(e);
    }
  }

  @action
  async sendsmsVerify(data,self){
      this.loading = true;
      var requestURL = api.smsVerify;
    
      try {
        const response = await axios.post(requestURL,data, {
          headers: {
            "Content-Type":'multipart/form-data'
          },
          timeout: 5000
        });
  
    
          this.loading = false;
          self.startToCountDown()
        console.log(response);

      } catch (e) {
        console.log(e);
        this.loading = false;
        self.handleNetworkFailed()
        self.refs.toast.show(e.response);
       
      
      }
  }

  @action
  async loginPost(data, self, navAction) {
    this.loading = true;
    var requestURL = api.login;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          "Content-Type": "application/json"
        },
        timeout: 5000
      });

      Global.login = true;
      transaction(() => {
        this.userData = response;
        this.logined = true;
        this.loading = false;
      });
      this.getCreditCard();
      this.notificationInit(response.data.member.id);
      console.log(response);
      if (navAction) {
        asyncStorageHelper.saveData("userInfo", data);
        self.navigatieAction("menu");
      }
    } catch (e) {
      self.refs.toast.show("Login Fail");
      this.loading = false;
      //connectFail.fail();
      console.log(e);
    }
  }

  @action
  async languageInit() {
    asyncStorageHelper.getData("language", lang => {
      if (lang != null) {
        console.log(lang);
        this.languageSelection = lang;
        this.changeLanguage(lang);
        console.log(this.languageSelection);
      }
    });
  }
  @action
  changeLanguage(lang) {
    console.log(lang);
    if (lang == "english") {
      console.log("select english");
      this.text = language.en;
    } else if (lang == "chinese") {
      console.log("select chinese");
      this.text = language.zh;
    }
  }
  @action
  dataLanguage(data, value) {
    if (this.languageSelection == "english") {
      switch (value) {
        case "name":
          return data.nameEn;
          break;
        case "addr":
          return data.addrEn;
          break;
          case "intro":
          return data.intro_en
          break;
          case 'placeName':
          return data.descriptionEn
          break;
      }
    } else {
      switch (value) {
        case "name":
          return data.name;
          break;
        case "addr":
          return data.addr;
          break;
          case "intro":
          return data.intro_ch
          break;
          case 'placeName':
          return data.description
          break;
      }
    }
  }
  @action
  saveLanguage(lang) {
    this.languageSelection = lang;
    this.changeLanguage(lang);
    asyncStorageHelper.saveString("language", lang);
  }

  @action
  async logoutPost(self,reset,data) {
    this.loading = true;
    var token = this.userData.data.token;
    var requestURL = api.logout;
    try {
      const response = await axios.post(requestURL, token);
      Global.login = false;
      this.regUserNotificationToken("");
      asyncStorageHelper.removeItemValue("userInfo");
      //asyncStorageHelper.removeItemValue("pickupPointId");
      if(reset){
        this.loginPost(data, self, true);
      }else{
  self.navigatieAction("menu");
      transaction(() => {
        this.userData = [];
        this.logined = false;
        this.creditCardinfo = {};
        this.addedCard = false;
        this.loading = false;
      });
      }
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }

  @action
  async pickupLoaction(self, pickupPointExist, pickupPointId) {
    var requestURL = api.pickUpLocation;
    console.log("userStore pickupPointId: " + pickupPointId);
    this.pickupPointId = pickupPointId;
    try {
      const response = await axios.get(requestURL);
      response.data.content.sort((a, b) => a.id - b.id);
      this.pickupLoactionPoint = response;
      console.log(this.pickupLoactionPoint);
      this.pickupPointLabel = [];
      response.data.content.forEach(element => {
        if(element.status == 'A'){
        var label = {
          value: element.name,
          id: element.id,
          name: element.name,
          nameEn: element.nameEn,
          pickupStartTime: element.pickupStartTime,
          pickupEndTime: element.pickupEndTime,
          photo: element.photo,
          lat: element.lat,
          lng: element.lng
        };
        var place = {
          description: element.name,
          descriptionEn: element.nameEn,
          geometry: { location: { lat: element.lat, lng: element.lng } },
          id: element.id,
          pickupTime: {
            pickupEndTime: element.pickupEndTime,
            pickupStartTime: element.pickupStartTime,
            orderEndTime: element.orderEndTime,
            orderStartTime: element.orderStartTime
          }
        };
        this.pickupPointLabel.push(label);
        this.perdefinedPlaces.push(place);
        
      }

      });
      
      if (!pickupPointExist) {
        this._requestPermission(self);
      } else {
        if(this.getIndex(pickupPointId) === -1){
          console.log("can't find index")
          self.navigatieAction('LocationRequest');
        }else{
          console.log("find index");
          self.getMenuItemFromInit();
        }
      }
    } catch (e) {
      console.log(e.message);
      Alert.alert(
        e.message,
        e.message,
        [
          {
            text: "Try again",
            onPress: () => {
              this.pickupLoaction(self, pickupPointExist, pickupPointId);
            }
          }
        ],
        { cancelable: false }
      );
    }
  }

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

   return index
   
   }

  _requestPermission(self) {
    Permissions.request("location").then(response => {
      // Returns once the user has chosen to 'allow' or to 'not allow' access
      // Response is one of: 'authorized', 'denied', 'restricted', or 'undetermined'
      // this.setState({ photoPermission: response })
      if (
        response == "allow" ||
        response == "restricted" ||
        response == "authorized"
      ) {
        navigator.geolocation.getCurrentPosition(
          position => {
            this.userLocation = position;
            console.log(position);
           // self.navigatieAction("LocationRequest");
           self.navigatieAction('Tutorial',{data:'store'})
          },
          error => {
            console.log(error);
            //self.navigatieAction("LocationRequest");
            self.navigatieAction('Tutorial',{data:'store'})
          },
          { enableHighAccuracy: false, timeout: 4000, maximumAge: 10000 }
        );
      } else {
       // self.navigatieAction("LocationRequest");
       self.navigatieAction('Tutorial',{data:'store'})
      }
    });
  }

  @action
  async getCreditCard() {
    var data = {};
    var requestURL = api.creditCard;
    var token = this.userData.data.token;
    try {
      const response = await axios.get(requestURL, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      console.log(response.data);
      if (response.data.content.length > 0) {
        this.addedCard = true;
        this.creditCardinfo = response.data.content[0];
      }
      //self.navigatieAction("menu");
    } catch (e) {
      console.log(e);
    }
  }

  @action
  async deleCreditCard(self) {
    this.loading = true;
    var token = this.userData.data.token;
    var requestURL = api.creditCard + "/" + this.creditCardinfo.id.toString();
    try {
      const response = await axios.delete(requestURL, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        },
        timeout: 5000
      });
      this.creditCardinfo = {}
      this.loading = false;
      this.addedCard = false;
      console.log(response);
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }

  @action
  async postCreditCard(self, data) {
    console.log(data);
    this.loading = true;
    var token = this.userData.data.token;
    var requestURL = api.creditCard;
    var testString = "cvc: " + data.cvc+" expiry: "+data.expiry+" num: "+data.num
   // self.testing(token,testString)

    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          Authorization: token,
          "Content-Type": "application/json"
        }
      });

      transaction(() => {
        this.creditCardinfo = response.data;
        this.loading = false;
        this.addedCard = true;
      });
      console.log(response);
      self.addCard = false;
      self.cardData = null;
      //navigation.goBack();
      // self.navigatieAction("menu");
    } catch (e) {
      this.loading = false;
      console.log(e);
      self.refs.toast.show(e.message);
    }
  }

  @action
  async signupPost(self) {
    this.loading = true;
    var requestURL = api.signup;
    try {
      const response = await axios.post(requestURL, this.signUpData, {
        headers: {
          "Content-Type": "application/json"
        }
      });

      transaction(() => {
        this.loading = false;
        this.isSignUp = false;
        this.isSignUpVerify = false;
        this.userData = response;
      });
      console.log(response);
      // self.navigatieAction("menu");
      var data = { id: this.signUpData.email, pwd: this.signUpData.pwd };
      this.loginPost(data, self, true);
    } catch (e) {
      console.log(e.response.data);
      self.refs.toast.show("SignUp Fail: "+ e.response.data);
      this.loading = false;
    }
  }

  @action
  async forgotPassword(data,self) {
    this.loading = true;
    var requestURL = api.forgotPassword;
    try {
      const response = await axios.post(requestURL, data, {
        headers: {
          "Content-Type": "application/json"
        }
      });   
        this.loading = false;
        if(!this.logined){
          self.backAction() 
        }else{
          self.password = "";
          self.verificationCode = "";
          self.handleStopCountdown()
          self.refs.toast.show("Reset Password success");
         // self.navigatieAction('menu');
         var data = {id:this.userData.data.member.email,pwd:data.password}
         this.logoutPost(self,true,data)
        }
         
      console.log(response);
    } catch (e) {
      console.log(e.response.data);
      self.refs.toast.show("Reset Password Fail: "+ e.response.data);
      this.loading = false;
    }
  }

  @action
  async checkMember(data, self) {
    this.loading = true;
    var requestURL = api.check;
    var checkData = {
      email: data.email,
      mobileWithCountryCode: data.countryCode + data.mobile
    };
    try {
      const response = await axios.post(requestURL, checkData, {
        headers: {
          "Content-Type": "application/json"
        }
      });
       console.log( response)
       console.log( response.data[Object.keys(response.data)[1]] +"  "+response.data[Object.keys(response.data)[0]])
      if (
        response.data[Object.keys(response.data)[1]] &&
        response.data[Object.keys(response.data)[0]]
      ) {
        transaction(() => {
          this.signUpData = data;
          this.loading = false;
        });

        self.navigatieAction("SignUpVerify");
        //this.isSignUpVerify = true;
      } else if (!response.data[Object.keys(response.data)[1]] && response.data[Object.keys(response.data)[0]]) {
        self.refs.toast.show("Sign up failed. Phone number already in use.");
        this.loading = false;
      } else if (!response.data[Object.keys(response.data)[0]]&& response.data[Object.keys(response.data)[1]]) {
        self.refs.toast.show("Sign up failed. Email already in use.");
        this.loading = false;
      }
    } catch (e) {
      self.refs.toast.show("SignUp Fail");
      this.loading = false;
      console.log(e);
    }
  }
}

const userStore = new User_store();

export default userStore;
