import {observable, action, transaction} from 'mobx';
import axios from 'axios';
import {NavigationActions} from 'react-navigation';
import language from '../services/language';
import AsyncStorageHelper from '../common/asyncStorageHelper';
import uuid from 'react-native-uuid';
import moment from 'moment';
import PushNotification from 'react-native-push-notification';
import Realm from 'realm';
import history from '../common/history';
import api from '../services/api';
var _ = require('lodash');
import {
  UserSchemea,
  ApartmentSchemea,
  DocSchemea,
  NotificationSchemea,
} from '../services/realm/schemeas';
import Global from '../services/Global';
const asyncStorageHelper = new AsyncStorageHelper();
let realm = new Realm({
  schema: [UserSchemea, ApartmentSchemea, DocSchemea, NotificationSchemea],
});
class AppStore {
  @observable
  text = language.en;
  @observable
  languageSelection = 'english';

  @observable
  logined = false;

  @observable
  addFunctionVisable = false;

  @observable
  loading = false;

  @observable
  list = [];

  apartment = null;

  @observable
  apartmentData = {
    id: null,
    createDate: null,
    modifyDate: null,
    avatar: null,
    apartmentName: null,
    address: null,
    signContractDate: null,
    endContractDate: null,
    rent: null,
    country: 'hk',
    CallingCode: '+852',
    rentNotification: 1,
    endContractNotification: 1,
    rentNotificationId: [],
    endContractNotificationId: null,
    remark: [],
    doc: [],
  };
  @observable
  apartmentDataRemark = [];
  @observable
  apartmentDataDoc = [];
  @observable
  avatar = null;
  @observable
  user = null;

  @observable
  image = null;

  @observable
  timer = 0;

  @action
  convertLocalIdentifierToAssetLibrary(localIdentifier, ext) {
    const hash = localIdentifier.split('/')[0];
    return `assets-library://asset/asset.${ext}?id=${hash}&ext=${ext}`;
  }

  @action
  getCountryLabel(value) {
    return this.text.CountryList[
      this.text.CountryList.findIndex(x => x.value === value)
    ].label;
  }

  @action
  setList(data) {
    this.list = data;
  }

  @action
  resetTimer() {
    this.timer = 0;
  }

  @action
  tick() {
    this.timer += 1;
  }
  @action
  idGenerator() {
    return uuid.v4();
  }

  @action
  resetApartmentData() {
    this.apartmentData = {
      id: null,
      createDate: null,
      modifyDate: null,
      avatar: null,
      apartmentName: null,
      address: null,
      signContractDate: null,
      endContractDate: null,
      rent: null,
      country: 'hk',
      CallingCode: '+852',
      rentNotification: 1,
      endContractNotification: 1,
      rentNotificationId: [],
      endContractNotificationId: null,
      remark: [],
      doc: [],
    };
    this.apartmentDataRemark = [];
    this.apartmentDataDoc = [];
    this.avatar = null;
  }

  @action
  rentlocalNotificationHandler() {
    if (this.apartmentData.rentNotification !== 0) {
      transaction(() => {
        this.apartmentData.rentNotificationId = [];
        var notificationDay = moment(
          this.apartmentData.signContractDate,
        ).subtract(this.apartmentData.rentNotification, 'days');
        var endday = moment(this.apartmentData.endContractDate);
        console.log(notificationDay.toDate());
        console.log(endday.toDate());
        while (notificationDay <= endday) {
          var id = this.idGenerator();
          this.apartmentData.rentNotificationId.push(id);
          var title = '收租提示';
          var normalDay = notificationDay.add(
            this.apartmentData.rentNotification,
            'days',
          );
          var conent =
            this.apartmentData.apartmentName +
            '的租客應在' +
            normalDay.format('DD-MM-YYYY') +
            '交租';
          this.pushNotification(title, conent, id, notificationDay.toDate());
          notificationDay = notificationDay.add(1, 'months');
          console.log(notificationDay.toDate());
        }
      });
    }
  }

  @action
  endContractlocalNotificationHandler() {
    if (this.apartmentData.endContractNotification !== 0) {
      this.apartmentData.endContractNotificationId = null;
      var endday = moment(this.apartmentData.endContractDate).subtract(
        this.apartmentData.endContractNotification,
        'days',
      );

      var id = this.idGenerator();
      this.apartmentData.endContractNotificationId = id;
      var title = '合約到期提示';
      var normalDay = endday.add(
        this.apartmentData.endContractNotification,
        'days',
      );
      var conent =
        this.apartmentData.apartmentName +
        '的租約會在' +
        normalDay.format('DD-MM-YYYY') +
        '到期';
      this.pushNotification(title, conent, id, endday.toDate());
    }
  }

  @action
  deleteNotification(index) {
    this.user.apartment[index].rentNotificationId.map((items, index) => {
      PushNotification.cancelLocalNotifications({id: items});
    });
    PushNotification.cancelLocalNotifications({
      id: this.user.apartment[index].endContractNotificationId,
    });
  }

  pushNotification(title, content, id, date) {
    this.lastId++;
    PushNotification.localNotificationSchedule({
      date: date, // in 30 secs
      id: id,
      userInfo: {
        id: id, //IMPORTANT!! adding the userInfo, so that the cancel will work!
      },

      number: 0,
      /* iOS only properties */
      alertAction: 'view', // (optional) default: view

      /* iOS and Android properties */
      title: title, // (optional)
      message: content, // (required)
      playSound: true, // (optional) default: true
      soundName: 'default', // (optional) Sound to play when the notification is shown. Value of 'default' plays the default sound. It can be set to a custom sound such as 'android.resource://com.xyz/raw/my_sound'. It will look for the 'my_sound' audio file in 'res/raw' directory and play it. default: 'default' (default sound is played)
    });
  }

  @action
  cloneApartmentData(index) {
    console.log('run clone');
    const data = this.user.apartment[index];
    this.apartmentData = {
      id: data.id,
      createDate: data.createDate,
      modifyDate: data.modifyDate,
      apartmentName: data.apartmentName,
      address: data.address,
      signContractDate: data.signContractDate,
      endContractDate: data.endContractDate,
      rent: data.rent,
      country: data.country,
      CallingCode: data.CallingCode,
      rentNotification: data.rentNotification,
      endContractNotification: data.endContractNotification,
      rentNotificationId: data.rentNotificationId,
      endContractNotificationId: data.endContractNotificationId,
    };
    this.avatar = _.cloneDeep(data.avatar);
    this.apartmentDataRemark = data.remark;
    var remark = [];
    data.remark.map((item, index) => {
      remark.push(item);
    });
    this.apartmentDataRemark = remark;
  }

  @action
  async cloneApartmentDocData(index) {
    const data = this.user.apartment[index].doc;
    var doc = [];
    await data.map((item, index) => {
      var newItems = item;
      doc.push(newItems);
    });
    this.apartmentDataDoc = doc;
  }

  @action
  async saveEdit(index) {
    var data = this.apartmentData;
    let user = realm.objects('User');
    await this.deleteNotification(index);
    await this.rentlocalNotificationHandler();
    await this.endContractlocalNotificationHandler();

    try {
      realm.write(() => {
        let newApartment = {
          id: data.id,
          createDate: data.createDate,
          modifyDate: new Date(),
          apartmentName: data.apartmentName,
          address: data.address,
          avatar: this.avatar,
          signContractDate: data.signContractDate,
          endContractDate: data.endContractDate,
          rent: parseInt(data.rent),
          country: data.country,
          CallingCode: data.CallingCode,
          rentNotification: data.rentNotification,
          endContractNotification: data.endContractNotification,
          rentNotificationId: data.rentNotificationId,
          endContractNotificationId: data.endContractNotificationId,
          remark: this.apartmentDataRemark,
          doc: this.user.apartment[index].doc,
        };
        user[0].apartment[index] = newApartment;
      });
    } catch (e) {
      console.log('Error on creation ' + e);
    }
  }

  @action
  saveDocEdit(index) {
    var data = this.apartmentDataDoc;
    let user = realm.objects('User');
    try {
      realm.write(() => {
        user[0].apartment[index].doc = this.apartmentDataDoc;
      });
    } catch (e) {
      console.log('Error on creation ' + e);
    }
  }

  @action
  getUser() {
    let user = realm.objects('User');
    for (let p of user) {
      this.user = p;
    }
  }

  @action
  async loadLocalData() {
    let user = await realm.objects('User');
    for (let p of user) {
      this.user = p;
    }
  }

  @action
  deleteApartment(index) {
    var data = this.apartmentData;
    let user = realm.objects('User');
    try {
      realm.write(() => {
        user[0].apartment.splice(index, 1);
      });
    } catch (e) {
      console.log('Error on creation ' + e);
    }
  }

  @action
  changeLanguage(lang) {
    console.log(lang);
    if (lang == 'english') {
      console.log('select english');
      this.text = language.en;
      this.languageSelection = 'english';
    } else if (lang == 'hk') {
      console.log('select hk');
      this.text = language.hk;
      this.languageSelection = 'hk';
    } else {
      console.log('select chinese');
      this.text = language.ch;
      this.languageSelection = 'ch';
    }
  }

  //api

  @action
  async signupPost(self, data) {
    console.log(data);
    console.log(api.signup);
    var jsonData = {
      fullname: data.fullname,
      email: data.email,
      gender: data.gender,
      countryCode: data.countryCode,
      chara: data.chara,
      age: data.age,
      pwd: data.pwd,
      phone: data.phone,
      // refcode: "",
      // ownerPhone: ""
    };
    this.loading = true;
    var requestURL = api.signup;
    try {
      const response = await axios.post(requestURL, jsonData, {
        headers: {
          'Content-Type': 'application/json',
        },
      });

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

  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);
        // history.push(self,'mainPage')
        self.props.navigation.navigate('mainPage');
      } else {
        asyncStorageHelper.saveData('userInfo', data);
        history.goBack(self);
      }
    } catch (e) {
      self.refs.toast.show('Login Fail');
      this.loading = false;
      //connectFail.fail();
      console.log(e);
    }
  }

  @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');
      if (reset) {
        this.loginPost(data, self, true);
      } else {
        transaction(() => {
          this.userData = {};
          this.logined = false;
          //this.creditCardinfo = {};
          //this.addedCard = false;
          this.loading = false;
        });
        self.props.navigation.navigate(
          'main',
          {},
          NavigationActions.navigate({routeName: 'home'}),
        );
      }
    } catch (e) {
      this.loading = false;
      console.log(e);
    }
  }
}

const appStore = new AppStore();
export {appStore};
