/**
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package mars.mobile;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;

import android.provider.Settings;
import android.util.Log;


import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Random;


import androidx.work.OneTimeWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private  String message,title,order_id ,notice_order_id,file_url,gcm_style,url,arg1,arg2,arg3;
    Bitmap imgBitmap;
    SharedPreferences prefs;
    SharedPreferences.Editor editor;

    private static final String TAG = "MyFirebaseMsgService";
    private int msg_count;
    private boolean ad_finded=false;
    private String sound;

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */

    /**
     * Called if InstanceID token is updated. This may occur if the security of
     * the previous token had been compromised. Note that this is called when the InstanceID token
     * is initially generated so this is where you would retrieve the token.
     */
    //@SuppressLint("WrongThread")
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.

        String Android_id = Settings.Secure.getString(getApplicationContext().getContentResolver(),
                Settings.Secure.ANDROID_ID);

        if(Android_id !=null && token !=null) {



            regist task1 = new regist();
       ///     task1.execute(getResources().getString(R.string.Server_regid_url), token, "111", "");
            //task1.execute(getResources().getString(R.string.Server_regid_url), token, Str_MyPhoneNumber, "");

            prefs = getSharedPreferences("pref", Context.MODE_PRIVATE);
            editor = prefs.edit();
            editor.putString("token", token);
            editor.commit();
//            regist task1 = new regist();
//            task1.execute(getResources().getString(R.string.Server_regid_url), token, Android_id, "");
            try {
                URL url = new URL(getResources().getString(R.string.Server_regid_url) + "?regid=" + token + "&Str_MyPhoneNumber=" + Android_id + "&index=" + "1" + "&Android_id=" + Android_id + "&alram=" + "1");
                url.openStream();
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        prefs = getSharedPreferences("pref", Context.MODE_PRIVATE);
        editor = prefs.edit();


        // TODO(developer): Handle FCM messages here.
        Log.d(TAG, "From: " + remoteMessage.getFrom());


        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());//키 및 벨류 {key1=keyvalue1, key2=keyvalue2}
            Log.d(TAG, "Message data payload key1's value: " + remoteMessage.getData().get("key1"));
            Log.d(TAG, "Message data payload key2's value: " + remoteMessage.getData().get("key2"));
            url = remoteMessage.getData().get("url");
            url =  url.replace("amp;amp;", "");
            file_url = remoteMessage.getData().get("file_url");
            title = remoteMessage.getData().get("title");
            message = remoteMessage.getData().get("message");
            arg1 = remoteMessage.getData().get("arg1");
            arg2 = remoteMessage.getData().get("arg2");
            editor.putBoolean("is_my_msg", true);//추가코드
            editor.putBoolean("message_found", true);//추가코드

            editor.putString("p_messsage",message);
            editor.putString("subject",title);
            editor.putString("weblink",url);
            editor.putString("imgUrl",file_url);
            editor.putString("arg1",arg1);
            editor.putString("param_intent_url",url);

            if (prefs.getInt("msg_count", 0) == 0){//추가코드
                editor.putInt("msg_count", 1);//추가코드
                msg_count=1;
            }
            else {
                 msg_count =  prefs.getInt("msg_count", 0);
                editor.putInt("msg_count",msg_count+1);
                msg_count = msg_count +1;
            }
            editor.commit();
            updateIconBadgeCount(getApplicationContext(), msg_count);


            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
             //   scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }

        }

        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            Log.d(TAG, "Message Notification Title: " + remoteMessage.getNotification().getTitle());
        }
        if(remoteMessage.getData().get("title")!=null && remoteMessage.getData().get("message")!=null)
      sendNotification(remoteMessage.getData().get("title"),remoteMessage.getData().get("message"));
     //   sendNotification(remoteMessage.getNotification().getBody());
        Intent intent = new Intent(getApplicationContext(),message_popup_Activity.class);



    }



     /**
     * Schedule a job using FirebaseJobDispatcher.
     */
   // private void scheduleJob() {
        // [START dispatch_job]
   //     FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
   //     Job myJob = dispatcher.newJobBuilder()
   //             .setService(MyJobService.class)
   //             .setTag("my-job-tag")
    //            .build();
    //    dispatcher.schedule(myJob);
        // [END dispatch_job]
    //}

     private void scheduleJob() {
         OneTimeWorkRequest workRequest = new OneTimeWorkRequest.Builder(MyWorker.class).build();
         WorkManager.getInstance(getApplicationContext()).enqueue(workRequest);
     }


    /**
     * Handle time allotted to BroadcastReceivers.
     */
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

    public void updateIconBadgeCount(Context context, int count) {

        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", getLauncherClassName(context));
        intent.putExtra("badge_count", count);
        // send
        sendBroadcast(intent);
    }

    private String getLauncherClassName(Context context) {

        String result = "";
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(getPackageName());

        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
        if(resolveInfoList != null && resolveInfoList.size() > 0) {
            Log.d(TAG,"getpackagemanager");
            return resolveInfoList.get(0).activityInfo.name;
        }
        Log.d(TAG,"no getpackagemanager");
        return result;
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     *
     */

    @SuppressLint("SuspiciousIndentation")
    private void sendNotification(String title, String message) {

        Random random = new Random();
        int m = random.nextInt(9999 - 1000) + 1000;
        Log.d(TAG, "intent_num: " + m);

        //추가된 코드
        // 날짜는 현재 날짜로 고정
        // 현재 시간 구하기
        long now = System.currentTimeMillis();
        Date date = new Date(now);
        // 출력될 포맷 설정
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy년 MM월 dd일");
        //etDate.setText(simpleDateFormat.format(date));
        String date_ = simpleDateFormat.format(date).toString();


        if(message.matches(".*광고.*"))  ad_finded = true;
        if(title.matches(".*광고.*"))  ad_finded = true;

        Boolean is_ad_push=prefs .getBoolean("ad_push_value", false);//현재 광고 수신 설정 값

        Log.d(TAG,"now_ad_finded="+ad_finded);
        DBHelper dbHelper = null;
        Boolean act_ad_push= false; // 광고 푸시를 실행해 줘도 되는 경우 true

        if(ad_finded==true && is_ad_push==true ) { // 광고가 왔고 광고 허락 유저 저장
            dbHelper = new DBHelper(getApplicationContext(), "MoneyBook.db", null, 1);
            dbHelper.insert( message, title,file_url,url,date_);
            act_ad_push= true;
        }
        else if(ad_finded==false) {//메시지 내용에 광고 없이 일반 푸시가 온경우 저장
            dbHelper = new DBHelper(getApplicationContext(), "MoneyBook.db", null, 1);
            dbHelper.insert( message, title,file_url,url,date_);
            act_ad_push= false;
        }
        else if(ad_finded==true && is_ad_push==false ){ // 광고가 왔고 광고 허락 하지 않은 유저
            act_ad_push= false;
        }
        Log.d(TAG,"act_ad_push="+act_ad_push);
        Boolean nomal_push_value=prefs.getBoolean("nomal_push_value", true);//현재 광고 수신 설정 값
        Log.d(TAG,"nomal_push_value="+prefs.getBoolean("nomal_push_value", false));

         Intent intent = new Intent(this, MainActivity.class);
        //PendingIntent pendingIntent = PendingIntent.getActivity(this, m, intent, PendingIntent.FLAG_IMMUTABLE);
       // intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("title", title);
        intent.putExtra("message", message);
        intent.putExtra("order_id", order_id);
        intent.putExtra("url", url);
        intent.putExtra("arg1", arg1);
        intent.putExtra("arg2", arg2);
        intent.putExtra("arg3", arg3);
        intent.putExtra("param_intent_url", url);  // paik
        intent.putExtra("file_url", file_url);
        //PendingIntent pendingIntent = PendingIntent.getActivity(this, m /* Request code */, intent,                PendingIntent.FLAG_CANCEL_CURRENT);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, m, intent, PendingIntent.FLAG_IMMUTABLE);

      String channelId = getString(R.string.default_notification_channel_id);
     ///   String channelId = "test2";
       Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      ///  Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
      ///  Uri defaultSoundUri  =  Uri.parse("android.resource://" + getPackageName() +"/"+ R.raw.mugo2);
        // Since android Oreo notification channel is needed.
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    getResources().getString(R.string.app_name)+"채널",
                    //  NotificationManager.IMPORTANCE_DEFAULT);
                    NotificationManager.IMPORTANCE_HIGH);
           // channel.setVibrationPattern(new long[]{0, 1000, 500, 1000});
            channel.enableVibration(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            notificationManager.createNotificationChannel(channel);
        }
        try {
            URL url = null;
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,channelId)
                    .setSmallIcon(getNotificationIcon())
                    // .setSmallIcon(R.mipmap.ic_launcher)
                    .setColor(Color.parseColor("#fdc61e"))
                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                    .setContentTitle(title)
                    .setContentText("두 손가락을 이용해 아래로 당겨 내용 확인")//본문내용
                    //  .addAction(R.mipmap.ic_launcher, "두손가락으로 여세요", pendingIntent)
                    .setAutoCancel(true)
                    .setTicker("새로운 메시지가 도착했습니다.")//추가코드
                    .setWhen(System.currentTimeMillis())//추가코드 지금당장
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
            notificationBuilder.setPriority(Notification.PRIORITY_MAX);
            //notificationBuilder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
            Log.d(TAG,"is_now_susin_vibe="+prefs.getBoolean("is_now_susin_vibe", true));
            if(prefs.getBoolean("is_now_susin_vibe", false)) {
                //notificationBuilder.setVibrate(new long[]{100, 100, 200, 200, 300, 300, 400, 400, 500, 500});
                notificationBuilder.setVibrate(new long[]{100, 100, 200, 200, 300});
            }

            if(prefs.getBoolean("is_now_susin_sound", true)) {
              //  notificationBuilder.setSound(defaultSoundUri);
            }
          //  notificationBuilder.setSound(defaultSoundUri);
            notificationBuilder.setVibrate(new long[]{100, 100, 200, 200, 300});





            if(file_url!=null) {
                url = new URL( file_url);
                Log.d(TAG,file_url+"noti image pass1");
                URLConnection conn = url.openConnection();
                conn.connect();
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                imgBitmap = BitmapFactory.decodeStream(bis);
                bis.close();

                NotificationCompat.BigPictureStyle style = new NotificationCompat.BigPictureStyle();
                style.setBigContentTitle(title);
                style.setSummaryText(message);
                style.bigPicture(imgBitmap);
                notificationBuilder.setStyle(style);
                if (Build.VERSION.SDK_INT >= 24 &&  (act_ad_push == true || nomal_push_value == true)) {
                    Intent popup_intent = new Intent(this, message_popup_Activity.class);
                    popup_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if(arg2.equalsIgnoreCase("1"))
                    getApplication().startActivity(popup_intent);
                    Log.d(TAG,"CCC");
                }else{
                    if (act_ad_push == true || nomal_push_value == true){
                    // notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
                    Intent popup_intent = new Intent(this, message_popup_Activity.class);
                        popup_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if(arg2.equalsIgnoreCase("1"))
                        getApplication().startActivity(popup_intent);
                    }
                }
            }else{

                NotificationCompat.BigTextStyle style = new NotificationCompat.BigTextStyle();
                style.setSummaryText("내용 보기 +");
                style.setBigContentTitle(title);
                // style.bigText("Mir's IT Blog adress is \"itmir.tistory.com\"," +  "Welcome to the Mir's Blog!! Nice to Meet you, this is Example JellyBean Notification");
                style.bigText(message);
                notificationBuilder.setStyle(style);
                if (Build.VERSION.SDK_INT >= 24 &&  (act_ad_push == true || nomal_push_value == true)) {
                    Intent popup_intent = new Intent(this, message_popup_Activity.class);
                    popup_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    if(arg2.equalsIgnoreCase("1"))
                    getApplication().startActivity(popup_intent);
                    Log.d(TAG,"DDD");
                }else{
                    if (act_ad_push == true || nomal_push_value == true) {
                        //   notificationManager.notify(m /* ID of notification */, notificationBuilder.build());
                        Intent popup_intent = new Intent(this, message_popup_Activity.class);
                        popup_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if(arg2.equalsIgnoreCase("1"))
                        getApplication().startActivity(popup_intent);
                    }
                }
            }

            notificationBuilder.setSound(defaultSoundUri);
            notificationBuilder.setVibrate(new long[]{100, 100, 200, 200, 300});
            notificationManager.notify(m /* ID of notification */, notificationBuilder.build());//추가된 코드


        }catch (Exception e){
            Log.d(TAG,file_url+"noti image exception"+e.toString());
        }



    }

    private int getNotificationIcon() {
        boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
      //  return useWhiteIcon ? R.mipmap.ic_launcher  : R.drawable.ic_stat_name;
        return useWhiteIcon ? R.mipmap.ic_launcher : R.mipmap.ic_launcher;
    }

    public class MyWorker extends Worker {
        public MyWorker(@NonNull Context context, @NonNull WorkerParameters params) {
            super(context, params);
        }

        @NonNull
        @Override
        public Result doWork() {
            Log.d("MyWorker", "백그라운드 작업 수행 중...");
            // 여기에서 백그라운드 작업을 처리하세요.
            return Result.success();
        }
    }




}


