package com.yutou.jianr_mg.views;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Switch;

import com.yutou.jianr_mg.Adapters.MagicTeamDataAdapter;
import com.yutou.jianr_mg.Data.TeamData;
import com.yutou.jianr_mg.Databases.JianRDataDataBase;
import com.yutou.jianr_mg.Tools.JianRUtils;
import com.yutou.jianr_mg.Tools.Utils;
import com.yutou.jianr_mg.services.MagicBoxService;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import Interfaces.MagicBoxInterface;

public class WarView {
    private JSONObject data,message,nMsg,nightData;
    private MagicTeamDataAdapter adapter;
    private JianRDataDataBase dataBase;
    private Context context;
    private int width=-1;
    private Handler handler;
    private boolean isNight=false;

    public WarView(Context context, JSONObject warData, int width, Handler handler){
        this.data=warData;
        this.context=context;
        this.width=width;
        this.handler=handler;
        try {
            message=new JSONObject(data.getString("message"));
        } catch (Exception ignored) {
        }
    }
    private Timer timer;
    private String md5="",nMd5="";
    public void update(MagicBoxService service, int width){
        try{
            this.width=width;
            params.weight=width;
            linearLayout.setLayoutParams(params);
            /*service.addInterface(new MagicBoxInterface() {
                @Override
                public void getData(String data) {
                    try {
                        JSONObject json=new JSONObject(data);//准备修复战斗剧透无法剧透夜战的BUG
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });*/
            if(timer==null){
                timer=new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        try{
                            WarView.this.data=service.getDealNode();
                            WarView.this.nightData=service.getGetWarResult();
                            WarView.this.message=new JSONObject(data.getString("message"));
                            //昼战
                            if(!Utils.getMD5(WarView.this.message.toString()).equals(md5)){
                                md5=Utils.getMD5(WarView.this.message.toString());

                                if((int)listView.getTag()==1){
                                    adapter.setData(JianRUtils.getEnemyTeam(message));
                                    listView.setTag(0);
                                }else {
                                    adapter.setData(JianRUtils.getUserTeam(message));
                                    listView.setTag(1);
                                }
                                System.out.println("更新数据："+adapter.getCount()+" "+listView.getTag());
                                System.out.println(adapter.getItem(0).toString());
                                handler.post(() -> adapter.notifyDataSetChanged());
                            }
                            //夜战
                            nMsg=new JSONObject(WarView.this.nightData.getString("message"));
                            isNight = !nMsg.isNull("extraProgress");
                            if(!Utils.getMD5(nMsg.toString()).equals(nMd5)){
                                System.out.println("夜战，TAG:"+listView.getTag());
                                nMd5=Utils.getMD5(nMsg.toString());
                                if(!nMsg.isNull("extraProgress")){
                                    if((int)listView.getTag()==1){
                                        System.out.println("夜战，敌舰");
                                        adapter.setData(JianRUtils.getNightEnemyTeam(nMsg));
                                        listView.setTag(0);
                                    }else {
                                        System.out.println("夜战，己方");
                                        adapter.setData(JianRUtils.getNightUserTeam(nMsg));
                                       listView.setTag(1);
                                    }
                                    System.out.println("更新夜战："+adapter.getCount()+" "+listView.getTag());
                                    System.out.println(adapter.getItem(0).toString());
                                    handler.post(() -> adapter.notifyDataSetChanged());
                                }
                            }

                        }catch (Exception  e){
                            e.printStackTrace();
                        }
                    }
                },0,500);
            }


        }catch (Exception e){
            e.printStackTrace();
        }
    }
    private  LinearLayout linearLayout;
    private Switch userTeam;
    private Button button;
    private ListView listView;
    private LinearLayout.LayoutParams params;
    public View initView() {
        if(linearLayout!=null){
            return linearLayout;
        }
        dataBase=JianRDataDataBase.init();
        linearLayout = new LinearLayout(context);
        params= new LinearLayout.LayoutParams(width, ViewGroup.LayoutParams.MATCH_PARENT);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setLayoutParams(params);
        linearLayout.setBackgroundColor(Color.WHITE);

        listView = new ListView(context);
        button = new Button(context);
        userTeam = new Switch(context);
        button.setText("切换队伍");
        button.setOnClickListener(view -> {
            if ((int) listView.getTag() == 1) {
                if(isNight){
                    adapter.setData(JianRUtils.getNightEnemyTeam(nMsg));
                }else {
                    adapter.setData(JianRUtils.getEnemyTeam(message));
                }
                listView.setTag(0);
            } else {
                if(isNight){
                    adapter.setData(JianRUtils.getNightUserTeam(nMsg));
                }else {
                    adapter.setData(JianRUtils.getUserTeam(message));
                }
                listView.setTag(1);
            }
            adapter.reload();
            adapter.notifyDataSetChanged();
        });
        linearLayout.addView(button);

        userTeam.setText("剧透");
        userTeam.setOnCheckedChangeListener((compoundButton, b) -> {
          //  adapter.setSpoiler(b);
           // adapter.notifyDataSetChanged();
        });
        linearLayout.addView(userTeam);

        adapter = new MagicTeamDataAdapter(JianRUtils.getUserTeam(message), context);
        ViewGroup.LayoutParams listParams=new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        listView.setAdapter(adapter);
        listView.setLayoutParams(listParams);
        listView.setTag(1);
        linearLayout.addView(listView);

        return linearLayout;
    }

    private JSONObject loadData(File file) {
        try {
            JSONObject json;
            BufferedReader reader = new BufferedReader(new FileReader(file));
            String str = "", tmp;
            while ((tmp = reader.readLine()) != null) {
                str += tmp;
            }
            reader.close();
            json = new JSONObject(str);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public void close(){
        timer.cancel();
        linearLayout.removeAllViews();
        linearLayout=null;
        timer=null;
    }

}
