package com.yutou.jianr_mg.views;

import android.app.ActivityOptions;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.alibaba.fastjson.JSON;
import com.yutou.jianr_mg.Data.GameInfoLog;
import com.yutou.jianr_mg.Data.MapNode;
import com.yutou.jianr_mg.Data.TeamData;
import com.yutou.jianr_mg.Data.UserTeam;
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.R;
import com.yutou.jianr_mg.Tools.JianRUtils;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapTopActivity extends AppCompatActivity {
    private LinearLayout listLayout, titleLayout;
    private ConstraintLayout main_layut;
    private TextView name;
    private String level_name;
    private String chapterName;
    private int limit = -1;
    private ListView listView;
    private Handler handler;
    private String teamData = null;
    private ArrayAdapter<String> adapter;
    private List<String> nodes;
    private List<MapNode> mapNodes;
    private List<GameInfoLog> logs;
    private int model = -1;
    private MapNode mapNode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item_maptop);
        level_name = getIntent().getStringExtra("level_name");
        chapterName = getIntent().getStringExtra("chapterName");
        model = getIntent().getIntExtra("data", -1);
        initView();
        switch (model) {
            case 0:
                mapNodes = new ArrayList<>();
                initData();
                break;
            case 1:
                mapNode = com.alibaba.fastjson.JSONObject.parseObject(getIntent().getStringExtra("mapNode"), MapNode.class);
                limit = 0;
                getData();
                break;
            default:
                initData();
        }

        handler = new Handler();


    }

    private void initView() {
        listLayout = findViewById(R.id.listLayout);
        main_layut = findViewById(R.id.main_layut);
        titleLayout = findViewById(R.id.titleLayout);
        listView = findViewById(R.id.listView);
        name = findViewById(R.id.title);
        main_layut.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        if (chapterName != null) {
            name.setText(chapterName);
        } else {
            name.setText(level_name);
        }
        listView.setOnItemClickListener((parent, view, position, id) -> {
            Intent intent = null;
            if (model == 0) {
                if (mapNode == null) {
                    intent = new Intent(MapTopActivity.this, MapTopActivity.class);
                    intent.putExtra("level_name", level_name);
                    intent.putExtra("chapterName", nodes.get(position));
                    intent.putExtra("mapNode", com.alibaba.fastjson.JSONObject.toJSONString(mapNodes.get(position)));
                    intent.putExtra("data", 1);
                }
            } else if (model == -1) {
                intent = new Intent(MapTopActivity.this, MapTopActivity.class);
                intent.putExtra("level_name", level_name);
                intent.putExtra("chapterName", nodes.get(position));
                intent.putExtra("data", 0);
            } else if (model == 1) {
                intent = new Intent(MapTopActivity.this, MapUserTeamActivity.class);
                intent.putExtra("data", JSON.toJSONString(logs.get(position)));
            }
            if (intent != null)
                startActivity(intent, ActivityOptions.makeSceneTransitionAnimation(MapTopActivity.this, name, "transitionTitle").toBundle());

        });
    }

    private void initData() {
        try {
            JSONObject json = new JSONObject();
            json.put("levelName", level_name);
            json.put("limit", limit);
            String url = HttpApi.MAPTOP_MAP_NODE;
            if (chapterName != null) {
                url = HttpApi.MAPTOP_MAP_DATA;
                json.put("chapterName", chapterName);
            }
            HttpUtils.post(HttpApi.HOME_URL + url, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        JSONArray data = json.getJSONArray("data");
                        nodes = new ArrayList<>();
                        if (model == 0) {
                            for (int i = 0; i < data.length(); i++) {
                                teamData = data.getJSONObject(i).toString();
                                MapNode mapNode = JSON.parseObject(data.getJSONObject(i).toString(), MapNode.class);
                                mapNodes.add(mapNode);
                                nodes.add(mapNode.getNode_name());
                            }
                        } else {

                            for (int i = 0; i < data.length(); i++) {
                                nodes.add(data.getString(i));
                            }
                        }
                        handler.post(() -> {
                            adapter = new ArrayAdapter<>(MapTopActivity.this, android.R.layout.simple_list_item_1, nodes);
                            listView.setAdapter(adapter);
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void httpError(Exception e) {

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

    private void getData() {
        try {
            logs = new ArrayList<>();
            nodes = new ArrayList<>();
            JSONObject json = new JSONObject();
            json.put("node", mapNode.getId());
            json.put("limit", limit);
            HttpUtils.post(HttpApi.HOME_URL + HttpApi.MAPTOP_USER_TEAM, json, new HttpInterface() {
                @Override
                public void httpGetData(String string, int code) {
                    try {
                        JSONObject json = new JSONObject(string);
                        JSONArray data = json.getJSONArray("data");
                        for (int i = 0; i < data.length(); i++) {
                            GameInfoLog log = JSON.parseObject(data.getJSONObject(i).toString(), GameInfoLog.class);
                            logs.add(log);
                            List<TeamData> teamData = JianRUtils.getUserTeam(new JSONObject(log.getMessage()));
                            Map<Integer, Integer> types = new HashMap<>();
                            String stype = "";
                            for (TeamData datum : teamData) {
                                if (types.containsKey(datum.getType())) {
                                    types.put(datum.getType(), types.get(datum.getType()) + 1);
                                } else {
                                    types.put(datum.getType(), 1);
                                }
                            }
                            for (Integer key : types.keySet()) {
                                try {
                                    stype += types.get(key) + JianRUtils.getShipTypeById(key).getShortname() + ",";
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }
                            nodes.add(stype);

                        }
                        handler.post(() -> {
                            adapter = new ArrayAdapter<>(MapTopActivity.this, android.R.layout.simple_list_item_1, nodes);
                            listView.setAdapter(adapter);
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                        System.out.println(string);
                    }
                }

                @Override
                public void httpError(Exception e) {

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