/**
 *
 */
package com.sipai.jspatrol.background.locationservice;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.sipai.jspatrol.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;


public class Utils {
    private static String CLOSE_BRODECAST_INTENT_ACTION_NAME="com.hdsx.background.locationservice.CloseService";
	private static SimpleDateFormat sdf = null;
    private static NotificationManager mNotificationManager;
    private final static String PRIMARY_CHANNEL = "bkswlocationservice";

	public synchronized static String formatUTC(long l, String strPattern) {
		if (TextUtils.isEmpty(strPattern)) {
			strPattern = "yyyy-MM-dd HH:mm:ss";
		}
		if (sdf == null) {
			try {
				sdf = new SimpleDateFormat(strPattern, Locale.CHINA);
			} catch (Throwable e) {
			}
		} else {
			sdf.applyPattern(strPattern);
		}
		return sdf == null ? "NULL" : sdf.format(l);
	}

	public static Intent getExplicitIntent(Context context, Intent implicitIntent) {
		if (context.getApplicationInfo().targetSdkVersion < Build.VERSION_CODES.LOLLIPOP) {
			return implicitIntent;
		}

		// Retrieve all services that can match the given intent
		PackageManager pm = context.getPackageManager();
		List<ResolveInfo> resolveInfo = pm.queryIntentServices(implicitIntent, 0);
		// Make sure only one match was found
		if (resolveInfo == null || resolveInfo.size() != 1) {
			return null;
		}
		// Get component info and create ComponentName
		ResolveInfo serviceInfo = resolveInfo.get(0);
		String packageName = serviceInfo.serviceInfo.packageName;
		String className = serviceInfo.serviceInfo.name;
		ComponentName component = new ComponentName(packageName, className);
		// Create a new intent. Use the old one for extras and such reuse
		Intent explicitIntent = new Intent(implicitIntent);
		// Set the component to be explicit
		explicitIntent.setComponent(component);

		return explicitIntent;
	}

	public static void saveFile(String toSaveString, String fileName, boolean append) {
		try {
			String sdCardRoot = Environment.getExternalStorageDirectory()
					.getAbsolutePath();
			File saveFile = new File(sdCardRoot + "/" + fileName);
			if (!saveFile.exists()) {
				File dir = new File(saveFile.getParent());
				dir.mkdirs();
				saveFile.createNewFile();
			}
			FileOutputStream outStream = new FileOutputStream(saveFile, append);
			outStream.write(toSaveString.getBytes());
			outStream.write("\n".getBytes());
			outStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void saveFile2(Context context,String toSaveString, String fileName, boolean append) {
		try {
			String mDownloadUrl = context.getExternalCacheDir().getPath();

			File dir = new File(mDownloadUrl);
			File mFile = new File(dir.getPath(),fileName);

			Log.e("下载地址下载地址下载地址", dir.getPath()+dir.getName()+"");

			if(!dir.exists()){
				dir.mkdirs();
			}

			FileOutputStream outStream = new FileOutputStream(mFile, append);
			outStream.write(toSaveString.getBytes());
			outStream.write("\n".getBytes());
			outStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	public static Notification buildNotification(Context context) {
        Notification notification = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(PRIMARY_CHANNEL,
                    "轨迹记录中...", NotificationManager.IMPORTANCE_DEFAULT);
            channel.setLightColor(Color.GREEN);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);

            getNotificationManager(context).createNotificationChannel(channel);
            Notification.Builder builder = new Notification.Builder(context,PRIMARY_CHANNEL)
//					.setChannelId(channel.getId())
                    .setContentText("巡检运行中...")
                    .setSmallIcon(R.mipmap.moudle_ipatrol_logo)
					.setVisibility(Notification.VISIBILITY_PRIVATE)
                    .setAutoCancel(true);
            notification = builder.build();
        } else {
            Notification.Builder builder = new Notification.Builder(context);
            builder.setSmallIcon(R.mipmap.moudle_ipatrol_logo);
            builder.setContentText("巡检运行中..." )
                    .setWhen(System.currentTimeMillis());
            notification = builder.build();
        }

		return notification;
	}

    private static NotificationManager getNotificationManager(Context context) {
        if (mNotificationManager == null) {
            mNotificationManager = (NotificationManager)context.getSystemService(
                    Context.NOTIFICATION_SERVICE);
        }
        return mNotificationManager;
    }

    public static void startWifi(Context context) {
		WifiManager wm = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		wm.setWifiEnabled(true);
		wm.reconnect();
	}

	public static boolean isWifiEnabled(Context context) {
		WifiManager wm = (WifiManager) context
				.getSystemService(Context.WIFI_SERVICE);
		return wm.isWifiEnabled();
	}

	public static String getManufacture(Context context) {
		return Build.MANUFACTURER;
	}

	public static Intent getCloseBrodecastIntent() {
		return new Intent(CLOSE_BRODECAST_INTENT_ACTION_NAME);
	}

	public static IntentFilter getCloseServiceFilter() {
		return new IntentFilter(CLOSE_BRODECAST_INTENT_ACTION_NAME);
	}

	public static class CloseServiceReceiver extends BroadcastReceiver {

		Service mService;

		public CloseServiceReceiver(Service service) {
			this.mService = service;
		}

		@Override
		public void onReceive(Context context, Intent intent) {
			if (mService == null) {
				return;
			}
			mService.onDestroy();
		}
	}
}
