package com.android.launcher3.settings.wifi;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.launcher3.Launcher;
import com.android.launcher3.R;
import com.android.launcher3.settings.AppInstallReceiver;
import com.android.launcher3.settings.MyJobService;
import com.secspace.lib.common.utils.Prefs;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import static android.app.job.JobInfo.BACKOFF_POLICY_EXPONENTIAL;
import static android.app.job.JobInfo.DEFAULT_INITIAL_BACKOFF_MILLIS;

public class WifiScanService extends Service {
    Context mContext;
    WifiAutoConnectManager mWifiAutoConnectManager;
    private int mJobId = 0;
    JobInfo.Builder builder;
    Notification notification;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (WifiManagerUtils.getInstance(mContext).isEnabled()) {
                List<ScanResult> wifiList = getWifiList();
                List<WifiInfoBean> wifiInfoBean = getWifiInfoBean();
                boolean isBreak = false;
                for (int i = 0; i < wifiList.size(); i++) {
                    for (int j = 0; j < wifiInfoBean.size(); j++) {
                        if (wifiList.get(i).SSID.equals(wifiInfoBean.get(j).getSsid())) {
                            if (!WifiManagerUtils.getInstance(mContext).isConnectedWifi()) {
                                mWifiAutoConnectManager.connect(wifiInfoBean.get(j).getSsid(), wifiInfoBean.get(j).getPwd(), WifiAutoConnectManager.WifiCipherType.WIFICIPHER_WPA, wifiInfoBean.get(j).getMac());
                                isBreak = true;
                                break;
                            }
                        }
                    }
                    if (isBreak) {
                        break;
                    }
                }
                WifiManagerUtils.getInstance(mContext).isIllegalWifi();
            }
            if (!Prefs.isAutoStartSelf(mContext)){
//                writeLog(timeStamp2Date(System.currentTimeMillis())+"\r\n");
//                mContext.startService(new Intent(mContext,WifiScanService.class));
            }
            sendEmptyMessageDelayed(1, 8000);
        }
    };
    private NetworkConnectChangedReceiver mNetworkConnectChangedReceiver;

    @Override
    public void onCreate() {
        super.onCreate();
        mWifiAutoConnectManager = new WifiAutoConnectManager(WifiManagerUtils.getInstance(this).getWifiManager());
        mContext = this;
        mHandler.sendEmptyMessage(1);
        builder = new JobInfo.Builder(mJobId++, new ComponentName(mContext.getPackageName(), MyJobService.class.getName()));
        Log.i("WifiScanService", "onCreate: ");
        registerNetworkReceiver();
//        initJobInfo();
        initNotifi();
    }

    private void initNotifi() {
        Notification.Builder builder = new Notification.Builder(this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, Launcher.class);
        builder.setContentIntent(PendingIntent.
                getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.launcher_in)) // 设置下拉列表中的图标(大图标)
                .setContentTitle("移动终端软件正在运行") // 设置下拉列表里的标题
                .setSmallIcon(R.drawable.launcher_in) // 设置状态栏内的小图标
                .setContentText("移动终端软件正在运行")// 设置上下文内容
                .setDefaults(NotificationCompat.FLAG_ONLY_ALERT_ONCE);
        notification = builder.build(); // 获取构建好的Notification;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mNetworkConnectChangedReceiver);

    }

    private void initJobInfo() {
        //设置需要的网络条件，有三个取值：
        //JobInfo.NETWORK_TYPE_NONE（无网络时执行，默认）、
        //JobInfo.NETWORK_TYPE_ANY（有网络时执行）、
        //JobInfo.NETWORK_TYPE_UNMETERED（网络无需付费时执行）
        builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
        builder.setBackoffCriteria(DEFAULT_INITIAL_BACKOFF_MILLIS, BACKOFF_POLICY_EXPONENTIAL);
        builder.setRequiresCharging(false);
        builder.setOverrideDeadline(5000);
        // Extras, work duration.

        // Schedule job
        Log.i("WifiScanService", "Scheduling job");
        JobScheduler tm = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        int schedule = tm.schedule(builder.build());
        Log.i("WifiScanService", "job schedule: " + schedule);
    }


    private void registerNetworkReceiver() {
        //wifi连接监听
        mNetworkConnectChangedReceiver = new NetworkConnectChangedReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        registerReceiver(mNetworkConnectChangedReceiver, filter);
    }

    private List<ScanResult> getWifiList() {
        WifiManager wifiManager = (WifiManager) mContext.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        if (!wifiManager.isWifiEnabled()) {
            wifiManager.setWifiEnabled(true);
        }
        wifiManager.startScan();
        List<ScanResult> wifiList = wifiManager.getScanResults();
        return wifiList;
    }

    private List<WifiInfoBean> getWifiInfoBean() {
        return Gson2ListHelper.stringWifiWhite2List(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        startForeground(110, notification);
        return super.onStartCommand(intent, flags, startId);
    }

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

    private void writeLog(String content) {
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/NetWork1.text");
        try {
            if (file == null) {
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(content.getBytes());
            raf.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String timeStamp2Date(long time) {
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time));
    }
}
