package jp.usaya.lib;

import android.content.Intent;
import android.os.Bundle;
// import com.google.firebase.messaging.MessageForwardingService;
import com.unity3d.player.UnityPlayer;
import com.unity3d.player.UnityPlayerActivity;
// import com.onevcat.uniwebview.AndroidPlugin;
import android.util.DisplayMetrics;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.*;
import android.net.Uri;
import android.util.Log;
import android.os.SystemClock;
import java.io.File;
import java.net.URLEncoder;
import java.util.*;

import android.content.Context;
import android.app.AlarmManager;
import android.app.PendingIntent;

import android.content.pm.ActivityInfo;

// public class UsayaUnityPlayerActivity extends com.unity3d.player.UnityPlayerActivity // NCMB使わない場合はこっち
public class UsayaUnityPlayerActivity extends com.nifcloud.mbaas.ncmbfcmplugin.UnityPlayerActivity
{
    public UsayaUnityPlayerActivity()
    {
    }

    protected void onNewIntent(Intent intent)
    {
  //       Intent message = new Intent(this, MessageForwardingService.class);
  //       message.setAction(MessageForwardingService.ACTION_REMOTE_INTENT);
  //    	message.putExtras(intent);
  // 		startService(message);
    }

    public void onCreate(Bundle savedInstanceState)
    {
        if(mUnityPlayer != null)
        {
            mUnityPlayer.quit();
            mUnityPlayer = null;
        }
        super.onCreate(savedInstanceState);
    }

    public float getHeightPixels()
    {
        DisplayMetrics dMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dMetrics);
        return dMetrics.heightPixels;
    }

    public float getWidthPixels()
    {
        DisplayMetrics dMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dMetrics);
        return dMetrics.widthPixels;
    }

    public float getPointHeight()
    {
        DisplayMetrics dMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dMetrics);
        return dMetrics.heightPixels / dMetrics.density;
    }

    public float getPointWidth()
    {
        DisplayMetrics dMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getRealMetrics(dMetrics);
        return dMetrics.widthPixels / dMetrics.density ;
    }

    public void forceOrientationPortrait(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    public void forceOrientationLandscape(){
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }

    public long elapsedRealtime(){
        return SystemClock.elapsedRealtime();
    }

    public void postTwitterOrFacebook(boolean isTwitter, String message, String url, String imagePath)
    {
        try
        {
            String name = isTwitter ? "com.twitter.android" : "com.facebook.katana";
            String type = imagePath.equals("") ? "text/plain" : getIntentTypeForImage(imagePath);
            Intent intent = createAppIntent(name, "android.intent.action.SEND", type);
            if(intent != null)
            {
                intent.putExtra("android.intent.extra.TEXT", (new StringBuilder(String.valueOf(message))).append(BR).append(url).toString());
                if(!imagePath.equals(""))
                    intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(new File(imagePath)));
                UnityPlayer.currentActivity.startActivity(intent);
                UnityPlayer.UnitySendMessage(UNITY_SEND_GAMEOBJECT, UNITY_SEND_CALLBACK, "0");
            } else
            {
                UnityPlayer.UnitySendMessage(UNITY_SEND_GAMEOBJECT, UNITY_SEND_CALLBACK, "1");
            }
        }
        catch(Exception e)
        {
            Log.e(TAG, "postTwitterOrFacebook", e);
            UnityPlayer.UnitySendMessage(UNITY_SEND_GAMEOBJECT, UNITY_SEND_CALLBACK, "2");
        }
    }

    public void createChooser(String message, String imagePath)
    {
        try
        {
            String type = imagePath.equals("") ? "text/plain" : getIntentTypeForImage(imagePath);
            Intent intent = createAppIntent(null, "android.intent.action.SEND", type);
            if(intent != null)
            {
                intent.putExtra("android.intent.extra.TEXT", message);
                if(!imagePath.equals(""))
                    intent.putExtra("android.intent.extra.STREAM", Uri.fromFile(new File(imagePath)));
                UnityPlayer.currentActivity.startActivity(Intent.createChooser(intent, "Share"));
                UnityPlayer.UnitySendMessage(UNITY_SEND_GAMEOBJECT, UNITY_SEND_CALLBACK, "0");
            } else
            {
                UnityPlayer.UnitySendMessage(UNITY_SEND_GAMEOBJECT, UNITY_SEND_CALLBACK, "1");
            }
        }
        catch(Exception e)
        {
            Log.e(TAG, "createChooser", e);
            UnityPlayer.UnitySendMessage(UNITY_SEND_GAMEOBJECT, UNITY_SEND_CALLBACK, "2");
        }
    }

    private String getIntentTypeForImage(String imagePath)
    {
        String extension = imagePath.substring(imagePath.lastIndexOf(".") + 1).toLowerCase(Locale.getDefault());
        return extension != ".png" ? "image/jpg" : "image/png";
    }

    private Intent createAppIntent(String name, String action, String type)
        throws Exception
    {
        Intent intent;
        List ris;
        Iterator iterator;
        try
        {
            intent = new Intent(action);
            intent.setType(type);
            ris = UnityPlayer.currentActivity.getPackageManager().queryIntentActivities(intent, 0x10000);
            if(name == "" || name == null)
                return ris.isEmpty() ? null : intent;
        }
        catch(Exception e)
        {
            throw e;
        }
        iterator = ris.iterator();
        while(iterator.hasNext()) 
        {
            ResolveInfo ri = (ResolveInfo)iterator.next();
            if(ri.activityInfo.packageName.equals(name))
            {
                intent.setClassName(ri.activityInfo.packageName, ri.activityInfo.name);
                return intent;
            }
        }
        return null;
    }

    public void sendNotification(long unixtime, int primary_key, String ticker, String content_title, String content_text, String sound_path)
    {
        // インテント作成
        Activity activity = UnityPlayer.currentActivity;
        Context context = activity.getApplicationContext();
        Intent intent = new Intent(context, NotificationReceiver.class);
        //渡す値
        intent.putExtra("PRIMARY_KEY", primary_key);
        intent.putExtra("TICKER", ticker);
        intent.putExtra("CONTENT_TITLE", content_title);
        intent.putExtra("CONTENT_TEXT", content_text);
        intent.putExtra("SOUND_PATH", sound_path);

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(unixtime);

        PendingIntent sender = PendingIntent.getBroadcast(context,  primary_key, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarm.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() , sender);
    }
    public void clearNotification(int primary_key)
    {
        // インテント作成
        Activity activity = UnityPlayer.currentActivity;
        Context context = activity.getApplicationContext();
        Intent intent = new Intent(context,NotificationReceiver.class);

        PendingIntent sender = PendingIntent.getBroadcast(context,  primary_key, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        AlarmManager alarm = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        alarm.cancel(sender);
        sender.cancel();
    }    

    public static final String TAG = "UsayaUnityPlayerActivity";
    public static final String BR = System.getProperty("line.separator");
    public static final String UNITY_SEND_GAMEOBJECT = "ShareManager";
    public static final String UNITY_SEND_CALLBACK = "OnShareManagerResult";
    public static final String RESULT_SUCCESS = "0";
    public static final String RESULT_NOT_AVAILABLE = "1";
    public static final String RESULT_ERROR = "2";


}