/*
 * The MIT License
 *
 * Copyright 2013 Masahiko, SAWAI <masahiko.sawai@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.example.hello.android.app_uuid_hello;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import java.util.UUID;

/**
 * インストールされたアプリケーション毎に固有となるID。
 *
 * アプリケーションを削除して、再インストールした場合、アプリケーションの管理画面から データを消去した場合には 再生成される。
 * アプリケーションを更新した場合には SharedPreferences は引き継がれるので再生成はされない。
 *
 * @author Masahiko, SAWAI <masahiko.sawai@gmail.com>
 */
public class ApplicationUUID
{

	private static final String LOG_TAG = "hello";
	private static String uuidString;

	public static String getUuid(Context context)
	{
		final String APP_UUID_KEY = "APP_UUID";
		Log.d(LOG_TAG, "uuidString 1 => " + uuidString);
		if (uuidString == null)
		{
			String packageName = context.getPackageName();
			SharedPreferences sharedPreferences = context.getSharedPreferences(packageName, Context.MODE_PRIVATE);
			uuidString = sharedPreferences.getString(APP_UUID_KEY, null);
			Log.d(LOG_TAG, "uuidString 2 => " + uuidString);
			if (uuidString == null)
			{
				// generate UUID
				UUID uuid = UUID.randomUUID();
				uuidString = uuid.toString();

				// save to SharedPreferences
				Editor edit = sharedPreferences.edit();
				edit.putString(APP_UUID_KEY, uuidString);
				edit.commit();

				Log.d(LOG_TAG, "uuidString 3 => " + uuidString);
			}
		}

		return uuidString;
	}
}
