package com.dahamit.dahammall;


import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.dahamit.dahammall.config.URLConfig;
import com.dahamit.dahammall.util.PreferManager;
import com.dahamit.dahammall.util.UtilClass;
import com.firebase.jobdispatcher.FirebaseJobDispatcher;
import com.firebase.jobdispatcher.GooglePlayDriver;
import com.firebase.jobdispatcher.Job;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "firebase";

    /**
     * Called when message is received.
     *
     * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
     */
    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
          // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            sendNotification(remoteMessage.getData().get("targeturl"), remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
        }
    }

    //  @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);


        sendRegistrationToServer(token);
    }

    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]
    }

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

    /**
     * Persist token to third-party servers.
     *
     * Modify this method to associate the user's FCM InstanceID token with any server-side account
     * maintained by your application.
     *
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    /*    String phoneNum = "";
        try{

            TelephonyManager telManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
            phoneNum = telManager.getLine1Number();
            if(phoneNum.startsWith("+82")){
                phoneNum = phoneNum.replace("+82", "0");
            }

        }catch(SecurityException e){


        }
        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder().add("Phone", phoneNum).add("Token", token).build();
        Request request = new Request.Builder().url("http://www.vilatalk.com/fcm/register_token.php").post(body).build();
        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        */
    }

    /**
     * Create and show a simple notification containing the received FCM message.
     *
     * @param messageBody FCM message body received.
     */
    private void sendNotification(String targeturl, String title, String messageBody) {

        Log.d(TAG,"in sendNotification");
        Log.d(TAG,"in sendNotification"+title);
        Log.d(TAG,"in sendNotification"+messageBody);
        Log.d(TAG,"in sendNotification"+targeturl);

        URLConfig.CURRENT_URL = targeturl;
        Log.d(TAG,"in sendNotification URLConfig.CURRENT_URL > "+ URLConfig.CURRENT_URL);

        Intent intent = new Intent(this, MainActivity.class);
      //  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra("targeturl",targeturl);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        String channelId = getString(R.string.default_notification_channel_id);
        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

      //  Log.d(TAG,"in sendNotification SettingActivity.thisMemberid > "+SettingActivity.thisMemberid);

        String isSound = PreferManager.getPreferences(  this,  "sound");
        String isMoving = PreferManager.getPreferences(this,  "moving");

        Bitmap mLargIconForNoti = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
        NotificationCompat.Builder notificationBuilder =
                new NotificationCompat.Builder(this, channelId)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle(title)
                        .setContentText(messageBody)
                        .setLights(Color.BLUE,1,1)
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                        .setLargeIcon(mLargIconForNoti)
                        .setAutoCancel(true)
                        .setContentIntent(pendingIntent);

        Log.d(TAG,"in sendNotification isSound > "+isSound);

        if(isSound != null && isSound.trim().equals("N")) {
            Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            notificationBuilder.setSound(uri);
            Log.d(TAG,"in sendNotification isSound >111 " );
        }
        Log.d(TAG,"in sendNotification isMoving > "+isMoving);
        if(isMoving != null && isMoving.trim().equals("Y")) {
            long[] v = {500,1000};
            notificationBuilder.setVibrate(v);
            Log.d(TAG,"in sendNotification isMoving > 11" );

        }
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // Since android Oreo notification channel is needed.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId,
                    "Channel human readable title",
                    NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(channel);
        }
        String sCurrentPushCont = PreferManager.getPreferences(this, "pushCount");
        int currentPuishCount =0;
        try{
            currentPuishCount = Integer.parseInt(sCurrentPushCont);
        }catch(Exception e){

        }
        String ptvMute = PreferManager.getPreferences(this, "tvMute");
        String isMute2 = PreferManager.getPreferences(this,"mute2");
        String strTimeStart = PreferManager.getPreferences(this,  "strTimeStart");
        String strTimeEnd = PreferManager.getPreferences(this,  "strTimeEnd");

        boolean isNoty = true;

        String today = null;
        Date date = new Date();
        System.out.println(date);
        // 포맷변경 ( 년월일 시분초)
        SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // Java 시간 더하기
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        today = sdformat.format(cal.getTime());

        int year = cal.get ( cal.YEAR );
        int month = cal.get ( cal.MONTH ) + 1 ;
        int cdate = cal.get ( cal.DATE ) ;

        String sYear = year+"";
        String sMonth ="";
        if(month < 10){
            sMonth = "0"+month;
        }else{
            sMonth = ""+month;
        }

        String sDate = "";
        if(cdate < 10){
            sDate = "0"+cdate;
        }else{
            sDate = ""+cdate;
        }

        String strToday = sYear+"-"+sMonth+"-"+sDate;


        Calendar cal2 = Calendar.getInstance();
        cal2.add(Calendar.DATE, 1);
        int year2 = cal.get ( cal2.YEAR );
        int month2 = cal.get ( cal2.MONTH ) + 1 ;
        int cdate2 = cal.get ( cal2.DATE ) ;

        String sYear2 = year2+"";
        String sMonth2 ="";
        if(month2 < 10){
            sMonth2 = "0"+month2;
        }else{
            sMonth2 = ""+month2;
        }

        String sDate2 = "";
        if(cdate2 < 10){
            sDate2 = "0"+cdate2;
        }else{
            sDate2 = ""+cdate2;
        }
        String strNextday = sYear2+"-"+sMonth2+"-"+sDate2;


         //1) 현재 시간이 5시간끄기 모드인지 확인
        if( UtilClass.isGreat(ptvMute, today)) {
            isNoty = false;
        }
        //2) 수동끄기가 체크되어 있는지
        if( isMute2 != null && isMute2.trim().equals("Y")) {
            isNoty = false;
        }else {
            isNoty = true;
        }
        //3) 수동끄기 시간인지
        if(!isNoty){
            String startDate ="";
            String endDate="";
            if( UtilClass.isGreat(strTimeEnd, strTimeStart)) {
                //3-1) 시작시간이 종료시간보다 적으면 동일
                startDate = strToday+" "+strTimeStart;
                endDate = strToday+" "+strTimeEnd;
            }else{
                //3-2) 시작시간이 종료시간보다 많으면 종료시간을 다음날로 한다
                startDate = strToday+" "+strTimeEnd;
                endDate = strNextday+" "+strTimeStart;
            }
            if( UtilClass.isGreat(today, strTimeStart) &&  UtilClass.isGreat(strTimeEnd, today) ){
                isNoty = false;
            }
        }
        if(isNoty){
            notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
        }
        currentPuishCount ++;
        PreferManager.savePreferences(this,"pushCount",currentPuishCount+"");
        Intent badgeIntent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");

        badgeIntent.putExtra("badge_count", currentPuishCount);
        badgeIntent.putExtra("badge_count_package_name", getPackageName());
        // badgeIntent.putExtra("badge_count_class_name", get());
        sendBroadcast(badgeIntent);


    }
}