package com.yutou.jianr_mg.services;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.widget.RemoteViews;

import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Data.TModfile;
import com.yutou.jianr_mg.Interfaces.DownloadFileInerface;
import com.yutou.jianr_mg.Interfaces.DownloadInterface;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.R;
import com.yutou.jianr_mg.Tools.Log;
import com.yutou.jianr_mg.Tools.Utils;

import java.util.ArrayList;
import java.util.List;


public class DownloadService extends Service {
    private List<TModfile> list;
    private DownloadInterface downloadInterface;
    private NotificationManager notificationManager;
    private String BUTTON_CLICK = "com.yutou.jianrmg.download.notification.button";
    private Download download;
    private RemoteViews views;
    private Notification notification;
    private boolean puase = false;
    private static boolean isInit = false;

    public class ServiceBinder extends Binder {
        public DownloadService getService(DownloadInterface downloadInterface) {
            DownloadService.this.downloadInterface = downloadInterface;
            return DownloadService.this;
        }
    }

    public DownloadService() {
        list = new ArrayList<>();
    }

    private ServiceBinder binder = new ServiceBinder();

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return binder;
    }

    public void setFiles(List<TModfile> list) {
        this.list = list;
    }

    public void setInterface(DownloadInterface downloadInterface) {
        this.downloadInterface = downloadInterface;
    }

    public int getDownloadList() {
        return list.size();
    }

    public void start(List<TModfile> addList) {
        Log.i("启动下载服务");
        list.addAll(addList);
        if (!isInit) {
            puase = false;
            downloadInterface.start();
            startNotification();
            download = new Download(this);
            isInit = true;
        }

    }

    public void pause() {
        puase = !puase;
    }

    private void startNotification() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BUTTON_CLICK);
        registerReceiver(receiver, filter);
        Intent intent = new Intent(BUTTON_CLICK);
        PendingIntent buttonIntent = PendingIntent.getBroadcast(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        views = new RemoteViews(getPackageName(), R.layout.notification_download_layout);
        views.setTextViewText(R.id.title, "开始下载");
        views.setOnClickPendingIntent(R.id.button, buttonIntent);
        views.setImageViewResource(R.id.imageView, R.mipmap.ic_launcher);

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder builder = new Notification.Builder(getApplicationContext());
        builder.setTicker("开始下载");
        builder.setContentTitle("正在下载");
        builder.setContent(views);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            builder.setVisibility(Notification.VISIBILITY_PUBLIC);
        }
        //通知栏显示图标
        builder.setSmallIcon(R.drawable.icon_download);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel("channel_1", "Message", NotificationManager.IMPORTANCE_HIGH);
            builder.setChannelId(channel.getId());
            notificationManager.createNotificationChannel(channel);
        }

        notification = builder.build();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notificationManager.notify(1, notification);
        Utils.toast(getApplicationContext(), "展示通知栏");
    }

    private boolean isClickButton = false;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i("点击按钮");
            puase = !puase;
            isClickButton = true;
        }
    };

    private class Download extends Thread {
        private Download download;
        private DownloadService service;
        private boolean isAlive = false, downloading = false;

        public Download(DownloadService service) {
            download = this;
            download.init(service);
        }

        private void init(DownloadService service) {
            if (!download.isAlive || !download.isAlive() || !download.isInterrupted()) {
                this.service = service;
                start();
            }
        }

        @Override
        public void run() {
            super.run();
            isAlive = true;
            Log.i("准备下载");
            while (service.list.size() > 0) {
                if (downloading) {
                    continue;
                }
                Log.i("开始下载:" + (downloading));
                downloading = true;
                final TModfile modfile = service.list.get(service.list.size() - 1);
                service.downloadInterface.getDownloadList(service.list.size());
                Log.i("下载地址", modfile.getServiceurl());
                HttpUtils.downloadFile(modfile.getServiceurl(), Utils.getAppPath() + "/" + modfile.getMid() + "/", new DownloadFileInerface() {

                    @Override
                    public boolean downloading(String fileName, int current, long length) {
                        service.views.setTextViewText(R.id.title, "正在下载：" + modfile.getFilename() + "(" + length / 1024 + "kb)");
                        service.views.setProgressBar(R.id.progressBar, 100, current, false);
                        if (isClickButton) {
                            if (service.puase) {
                                service.views.setTextViewText(R.id.button, "下载");
                            } else {
                                service.views.setTextViewText(R.id.button, "暂停");
                            }
                            isClickButton = false;
                        }
                        try {
                            service.notificationManager.notify(1, service.notification);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        return !service.puase;
                    }

                    @Override
                    public void over(boolean isOver) {
                        if (isOver) {
                            service.list.remove(modfile);
                        }
                        downloading = false;
                    }
                });

            }
            AppData.handler.postDelayed(() -> {
                service.views.setTextViewText(R.id.button, "0v0");
                service.views.setTextViewText(R.id.title, "全部下载完成");
                service.views.setProgressBar(R.id.progressBar, 10, 10, false);
                service.notificationManager.notify(1, service.notification);
                service.downloadInterface.over();
                isAlive = false;
            }, 100);
            isInit=false;
            Log.i("下载结束");
        }
    }
}
