package com.casic.dcms.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

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

import com.amap.api.location.AMapLocation;
import com.casic.dcms.R;
import com.casic.dcms.utils.LocaleConstant;
import com.casic.dcms.utils.LocationHelper;
import com.casic.dcms.utils.callback.ILocationListener;
import com.casic.dcms.view.MainActivity;

/**
 * APP前台服务，降低APP被系统杀死的可能性
 */
public class UpdateLocationService extends Service {

    private static final String TAG = "UploadLocationService";
    private final Handler updateHandler = new Handler(Looper.getMainLooper());
    private final int notificationId = 1;
    private NotificationManager notificationManager;
    private NotificationCompat.Builder notificationBuilder;
    private long runningTime = 0L;

    @Override
    public void onCreate() {
        super.onCreate();
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        String name = getResources().getString(R.string.app_name) + "后台定位服务";
        NotificationChannel channel = new NotificationChannel(
                "update_location_service_channel", name, NotificationManager.IMPORTANCE_HIGH
        );
        channel.setDescription("Channel for Location Service");
        notificationManager.createNotificationChannel(channel);
        notificationBuilder = new NotificationCompat.Builder(this, "update_location_service_channel")
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("已运行0小时0分钟")
                .setContentText(LocaleConstant.FOREGROUND_RUNNING_SERVICE_TITLE)
                .setPriority(NotificationCompat.PRIORITY_HIGH) // 设置通知优先级
                .setOngoing(true)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC);

        Notification notification = notificationBuilder.build();
        startForeground(notificationId, notification);

        LocationHelper.get().getCurrentLocation(this, new ILocationListener() {

            @Override
            public void onAMapLocationGet(AMapLocation aMapLocation) {
                Message message = MainActivity.weakReferenceHandler.obtainMessage();
                message.what = LocaleConstant.UPDATE_LOCATION;
                message.obj = aMapLocation;
                MainActivity.weakReferenceHandler.sendMessage(message);
            }
        }, false);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        //记录通知被创建的时间
        runningTime = System.currentTimeMillis();
        Runnable updateRunnable = new Runnable() {
            @Override
            public void run() {
                updateNotification();
                updateHandler.postDelayed(this, 1000L * 60);
            }
        };
        updateHandler.post(updateRunnable);
        return START_STICKY;
    }

    private void updateNotification() {
        // 计算运行时长
        long elapsedTime = System.currentTimeMillis() - runningTime;
        int hours = (int) (elapsedTime / (1000 * 60 * 60));
        int minutes = (int) (elapsedTime % (1000 * 60 * 60) / (1000 * 60));

        notificationBuilder.setContentTitle("已运行" + hours + "小时" + minutes + "分钟");
        Notification notification = notificationBuilder.build();
        notificationManager.notify(notificationId, notification);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LocationHelper.get().stopLocation();
        updateHandler.removeCallbacksAndMessages(null);
        stopForeground(STOP_FOREGROUND_REMOVE);
        Log.d(TAG, "onDestroy: 停止后台定位服务");
    }
}