package com.dbs.mplus.fatima.service;

import java.io.IOException;

import com.dbs.mplus.fatima.framework.util.MPlusGCMUtil;
import com.dbs.mplus.fatima.framework.util.MPlusLogUtil;
import com.dbs.mplus.fatima.framework.util.MPlusPreferenceUtil;
import com.dbs.mplus.fatima.util.IntentUtil;

import android.app.IntentService;
import android.content.Intent;
import android.support.v4.content.LocalBroadcastManager;

/**
 * DeviceToken이 없다면 받아두기 위함 
 * 
 * @author aple
 *
 */
public class DeviceTokenPrepareService extends IntentService {
	private final Object syncObj = new Object(); 
	
	/**
	 * 생성자 
	 */
	public DeviceTokenPrepareService() { 
		super(DeviceTokenPrepareService.class.getName());
	}
	
	@Override 
	protected void onHandleIntent(Intent intent) { 
		MPlusLogUtil.DEBUG(this.getClass(), "intent : " + intent);
		
		synchronized(syncObj) { 
			final LocalBroadcastManager manager = LocalBroadcastManager.getInstance(this.getApplicationContext()); 
			
			try { 
				// 저장된 토큰이 있는지 확인하고 
				final MPlusPreferenceUtil p = MPlusPreferenceUtil.getInstance(this.getApplicationContext());
				String token = p.getDeviceToken(); 
				
				// 토근이 있는지 응답 
				if(token != null) { 
					manager.sendBroadcast(IntentUtil.getDeviceTokenPrepareComplete(true));
				}
				// 토큰이 없다면 발급받기 
				else {
					// 토큰 발급받고 
					token = MPlusGCMUtil.getDeviceToken(this.getApplicationContext());
					// 발급 안됐으면 
					if(token == null) { 
						// 실패 알려주기 
						manager.sendBroadcast(IntentUtil.getDeviceTokenPrepareComplete(false)); 
					}
					else { 
						// 저장하고 
						MPlusPreferenceUtil.getInstance(this.getApplicationContext()).setDeviceToken(token);
						// 알려주기 
						manager.sendBroadcast(IntentUtil.getDeviceTokenPrepareComplete(true));
					}					
				}
			}
			catch(final IOException ex) { 
				MPlusLogUtil.ERROR(DeviceTokenPrepareService.class, "fail to get token", ex);
				manager.sendBroadcast(IntentUtil.getDeviceTokenPrepareComplete(false)); 
			}
		}
	}
	
}