package com.yutou.jianr_mg.views;

import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.qq.e.comm.util.StringUtil;
import com.yutou.jianr_mg.Data.AppData;
import com.yutou.jianr_mg.Interfaces.DownloadFileInerface;
import com.yutou.jianr_mg.Interfaces.HttpInterface;
import com.yutou.jianr_mg.Network.HttpApi;
import com.yutou.jianr_mg.Network.HttpUtils;
import com.yutou.jianr_mg.Tools.CDNTools;
import com.yutou.jianr_mg.Tools.SocketTools;
import com.yutou.jianr_mg.Tools.Utils;

import org.json.JSONObject;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import me.drakeet.materialdialog.MaterialDialog;

public class GameDataActivity extends AppCompatActivity implements View.OnClickListener {
    private LinearLayout layout;
    private Button upload, download, localSocket;
    private TextView textView;
    private String token = null;
    private long credit;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        setContentView(layout);
        initData();
    }

    private void initView() {
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layout = new LinearLayout(this);
        upload = new Button(this);
        download = new Button(this);
        localSocket = new Button(this);
        textView = new TextView(this);

        upload.setLayoutParams(buttonParams);
        download.setLayoutParams(buttonParams);
        textView.setLayoutParams(buttonParams);
        localSocket.setLayoutParams(buttonParams);

        upload.setText("上传");
        download.setText("下载");
        localSocket.setText("局域网内设备同步");

        upload.setTag(1);
        download.setTag(2);
        localSocket.setTag(3);
        upload.setOnClickListener(this);
        download.setOnClickListener(this);
        localSocket.setOnClickListener(this);


        layout.addView(textView);
        layout.addView(upload);
        layout.addView(download);
        layout.addView(localSocket);
        layout.setOrientation(LinearLayout.VERTICAL);
    }

    private void initData() {
        try {
            JSONObject json = new JSONObject();
            json.put("gameDataSize", new File("/data/data/" + getPackageName() + "/databases/game_data_db").length());
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.DATA_UP_GAMEDATA, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        System.out.println(string);
                        JSONObject json = new JSONObject(string);
                        if (json.getInt("code") == 100) {
                            String token = json.getJSONObject("data").getString("token");
                            credit = json.getLong("credit");
                            if (!Utils.testStringIsNull(token)) {
                                GameDataActivity.this.token = token;
                            } else {
                                Utils.toast(GameDataActivity.this, "无法上传，请检查积分是否足够");
                            }
                        }
                        int upindex = json.getJSONObject("data").getInt("upindex");
                        long uptime = json.getJSONObject("data").getLong("uptime");
                        if (upindex == 0 && uptime == 0) {
                            AppData.handler.post(() -> textView.setText("您还未上传过数据"));
                        } else {
                            AppData.handler.post(() -> textView.setText("最后一次上传时间:" + SimpleDateFormat.getDateTimeInstance(DateFormat.YEAR_FIELD, DateFormat.SHORT).format(new Date(uptime))
                                    + "\n上传次数：" + upindex));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {

                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onClick(View v) {
        switch (Integer.parseInt(v.getTag() + "")) {
            case 1:
                if (token == null) {
                    Utils.toast(GameDataActivity.this, "无法上传，请检查积分是否足够");
                    return;
                }

                MaterialDialog upDialog = new MaterialDialog(this);
                upDialog.setTitle("上传数据");
                upDialog.setMessage("本次预计消耗积分：" + credit);
                upDialog.setPositiveButton("确定", v1 -> {
                    File file=new File("/data/data/" + getPackageName() + "/databases/game_data_db");
                    CDNTools.getInstance(GameDataActivity.this).upload(file, AppData.user.getId()+"/gamedata/"+file.getName(),token);
                    upDialog.dismiss();
                });
                upDialog.setNegativeButton("取消", v1 -> {
                    upDialog.dismiss();
                });
                upDialog.show();
                break;
            case 2:
                try {
                    JSONObject json = new JSONObject();
                    HttpUtils.post(HttpApi.HOME_URL + HttpApi.DATA_DOWN_GAMEDATA, json, new HttpInterface() {
                        KProgressHUD hd;

                        @Override
                        public void httpGetData(String string, int code) {
                            try {
                                JSONObject json = new JSONObject(string);
                                JSONObject data = json.getJSONObject("data");
                                String url = data.getString("url");
                                if (!StringUtil.isEmpty(url)) {
                                    AppData.handler.post(() -> {
                                        hd = Utils.showLoading(GameDataActivity.this, null, null);
                                        hd.show();
                                    });
                                    File file=new File("/data/data/" + getPackageName() + "/databases/game_data_db");
                                    file.delete();
                                    file=new File("/data/data/" + getPackageName() + "/databases/game_data_db-shm");
                                    file.delete();
                                    file=new File("/data/data/" + getPackageName() + "/databases/game_data_db-wal");
                                    file.delete();

                                    HttpUtils.downloadFile(url, "/data/data/" + getPackageName() + "/databases/", new DownloadFileInerface() {
                                        @Override
                                        public boolean downloading(String fileName, int current, long length) {
                                            AppData.handler.post(() -> hd.setLabel("下载中(" + current + ")"));
                                            return true;
                                        }

                                        @Override
                                        public void over(boolean isOver) {
                                            AppData.handler.post(() -> {
                                                hd.dismiss();
                                                Utils.toast(GameDataActivity.this,"重启生效~");
                                            });
                                        }
                                    });
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void httpError(Exception e) {

                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            case 3:
                MaterialDialog dialog = new MaterialDialog(this);
                dialog.setTitle("传输模式");
                dialog.setMessage("请选择传输模式？（请确保在同一个局域网下");
                dialog.setCanceledOnTouchOutside(true);
                dialog.setNegativeButton("接受模式", v1 -> {
                    dialog.dismiss();
                    new SocketTools(this, true, new HttpInterface() {
                        @Override
                        public void httpGetData(String string, int code) {
                            System.out.println(string);
                        }

                        @Override
                        public void httpError(Exception e) {

                        }
                    });
                });
                dialog.setPositiveButton("传输模式", v1 -> {
                    dialog.dismiss();
                    new SocketTools(this, false, new HttpInterface() {
                        @Override
                        public void httpGetData(String string, int code) {

                        }

                        @Override
                        public void httpError(Exception e) {

                        }
                    });
                });
                dialog.show();
                break;
        }
    }
}
