import {
    REMINDER_FETCH,
    REMINDER_CREATE,
    REMINDER_UPDATE,
    REMINDER_DELETE
} from './../actions/types'
import realm from './../Database/'
import moment from 'moment'
import { scheduleLocalNotification, cancleNotification } from './../Utils'
import { ToastAndroid } from 'react-native'

export const reminderCreate = ({ id, medName, reminderTime, meal, period, dose }) => {
    return (dispatch) => {
        let isPast = moment().diff(reminderTime)
        if (isPast > 0) {
            reminderTime = new Date(moment(reminderTime).add(1, 'day'))
        }
        ToastAndroid.show(isPast.toString(), ToastAndroid.SHORT)
        realm.write(() => {
            realm.create('Reminder', {
                id: id,
                medName: medName,
                reminderTime: reminderTime,
                meal: meal,
                period: period,
                dose: dose,
                timeStamp: moment().toDate()
            })
        })
        var time = moment(reminderTime).format('HH:mm').split(':')
        var msg = "แจ้งเตือนกินยา\n" + "เวลา: " + time[0] + ":" + time[1] + "\nยา: " + medName + '\n' + meal;
        scheduleLocalNotification(msg, reminderTime, id)
        let reminders = realm.objects("Reminder")
        dispatch({ type: REMINDER_CREATE, payload: reminders })
    }
}

export const reminderUpdate = () => {
    return (dispatch) => {

    }
}

export const reminderFetch = () => {
    return (dispatch) => {
        let reminders = realm.objects("Reminder")
        dispatch({ type: REMINDER_FETCH, payload: reminders })
    }
}

export const reminderDelete = (id) => {
    return (dispatch) => {
        let item = realm.objects("Reminder").filtered('id == ' + '"' + id + '"')
        realm.write(() => {
            realm.delete(item)
        })
        cancleNotification(id)
        let reminders = realm.objects("Reminder")
        dispatch({ type: REMINDER_DELETE, payload: reminders })
    }
}
