import Constants from 'expo-constants';
import * as Permissions from 'expo-permissions';
import * as Notifications from 'expo-notifications';
import { fetchPost } from './fetch';
import { showMessage } from '~/Components/UIControls/Message';

export const NotificationUtil = {
  registerForPushNotificationsAsync: async () => {
    try {
      if (Constants.isDevice) {
        console.log('=============== device ================');
        const { status: existingStatus } = await Permissions.getAsync(Permissions.NOTIFICATIONS);
        let finalStatus = existingStatus;
        if (existingStatus !== 'granted') {
          const { status } = await Permissions.askAsync(Permissions.NOTIFICATIONS);
          finalStatus = status;
        }
        if (finalStatus !== 'granted') {
          console.log('== Push 알림 권한이 설정되지 않았습니다. ==');
          return '푸시 알림 권한이 설정되지 않았습니다.';
        }
        const token = await Notifications.getExpoPushTokenAsync();
        console.log('=====================================');
        console.log('Push Token : ', token);
        console.log('=====================================');

        if (Platform.OS === 'android') {
          Notifications.setNotificationChannelAsync('default', {
            name: '알림',
            sound: 'default',
            vibrationPattern: [0, 250, 250, 250],
          });
        }

        return token;
      } else {
        console.log('== 물리적 장치를 사용해야 푸시알림이 가능합니다. ==');
        return '물리적 장치를 사용해야 푸시알림이 가능합니다.';
      }
    } catch(error) {
      console.log(error);
      return error;
    }
  },

  updatePushToken: async (siteId, userId, token = null) => {
    if(token == null) {
       token = await NotificationUtil.registerForPushNotificationsAsync();
    }

    if(token != null && typeof token === 'object') {
      try {
        await fetchPost('/api/app/users/UpdatePushToken', { 
            SiteId: siteId, 
            UserId: userId, 
            Devicetoken: token.data,
        });
        return '';
      } catch(error) {
        console.log(error);
        return error;
      }
    } else {
      return token;
    }
  }
}