import {
    APPOINTMENT_FETCH,
    APPOINTMENT_CREATE,
    APPOINTMENT_UPDATE,
    APPOINTMENT_DELETE
} from './../actions/types'
import realm from './../Database/'
import moment from 'moment'
import { appointmentNotification, cancleNotification } from './../Utils'

export const appointmentCreate = ({ id, doctorName, date, place, time }) => {
    return (dispatch) => {
        realm.write(() => {
            realm.create('Appointments', {
                id: id,
                doctorName: doctorName,
                date: date,
                place: place,
                timeStamp: moment().toDate()
            })
        })
        var time = moment(date).format('HH:mm').split(':')
        var msg = "แจ้งเตือนนัดพบแพทย์\n" + "แพทย์: " + doctorName + "\nเวลา: " + time[0] + ":" + time[1];
        appointmentNotification(msg, date, id)
        let appointments = realm.objects("Appointments")
        dispatch({ type: APPOINTMENT_CREATE, payload: appointments })
    }
}

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

    }
}

export const appointmentFetch = () => {
    return (dispatch) => {
        let appointments = realm.objects("Appointments")
        dispatch({ type: APPOINTMENT_FETCH, payload: appointments })
    }
}

export const appointmentDelete = (id) => {
    return (dispatch) => {
        let item = realm.objects("Appointments").filtered('id == ' + '"' + id + '"')
        realm.write(() => {
            realm.delete(item)
        })
        cancleNotification(id)
        let appointments = realm.objects("Appointments")
        dispatch({ type: APPOINTMENT_DELETE, payload: appointments })
    }
}
