package com.tsi.navi.activity.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.tsi.navi.R;
import com.tsi.navi.activity.adapter.UserSignalItemAdapter;
import com.tsi.navi.activity.model.SignalItem;
import com.tsi.navi.activity.model.CpuControl;
import com.tsi.navi.dto.CpuNodeStatusDTO;
import com.tsi.navi.vo.NodeVo;

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

public class UserSignalFragment extends Fragment {
    private static final String TAG = UserSignalFragment.class.getSimpleName();

    private Context context;
    private TextView tvName;
    private TextView tvId;
    private TextView tvCycle;
    private TextView tvTime;
    private TextView[] tvStatus = new TextView[CpuControl.MAX_STATUS];

    private int normalTextColor;
    private int activeTextColor;

    private NodeVo node;
    private long nodeId;
    private CpuControl cpuControl;

    private boolean first;
    private Map<Integer, SignalItem> directions = new HashMap<>();
    private RecyclerView recyclerView;
    private UserSignalItemAdapter UserSignalItemAdapter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_user_signal, container, false);

        this.first = false;

        this.tvName = v.findViewById(R.id.tv_name);
        this.tvId = v.findViewById(R.id.tv_id);
        this.tvCycle = v.findViewById(R.id.tv_cycle);
        this.tvTime = v.findViewById(R.id.tv_time);

        this.tvStatus[0] = v.findViewById(R.id.tv_status1); // 전이
        this.tvStatus[1] = v.findViewById(R.id.tv_status2); // 감응
        this.tvStatus[2] = v.findViewById(R.id.tv_status3); // 소등
        this.tvStatus[3] = v.findViewById(R.id.tv_status4); // 점멸
        this.tvStatus[4] = v.findViewById(R.id.tv_status5); // 수동

        this.UserSignalItemAdapter = new UserSignalItemAdapter(context, null);
        this.recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
        this.recyclerView.setAdapter(UserSignalItemAdapter);
        this.recyclerView.setLayoutManager(new LinearLayoutManager(context));

        this.normalTextColor = ContextCompat.getColor(this.context, R.color.rect_normal_color);
        this.activeTextColor = ContextCompat.getColor(this.context, R.color.rect_active_color);

        this.cpuControl = new CpuControl();
        this.nodeId = 0;

        return v;
    }

    @SuppressLint("ObsoleteSdkInt")
    protected void init() {
        if (this.node != null) {
            this.tvName.setText(this.node.getName());
            this.tvId.setText(String.valueOf(this.node.getNodeId()));
            this.nodeId = this.node.getNodeId();
        }
        else {
            this.tvName.setText("-");
            this.tvId.setText("???");
            this.nodeId = 0;
        }
        this.tvCycle.setText("-");
        this.tvTime.setText("현장시각");
        for (int ii = 0; ii < CpuControl.MAX_STATUS; ii++) {
            if (this.tvStatus[ii].getAnimation() != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                    this.tvStatus[ii].getAnimation().cancel();
                }
                this.tvStatus[ii].clearAnimation();
                this.tvStatus[ii].setAnimation(null);
            }
            if (ii == 3) {
                this.tvStatus[ii].setBackgroundResource(R.drawable.rect_border);  // 점멸
            }
            else {
                this.tvStatus[ii].setBackgroundResource(R.drawable.rect_none);    // 수동
            }
            this.tvStatus[ii].setTextColor(this.normalTextColor);
        }
        this.cpuControl.init();

        this.UserSignalItemAdapter.setItems(null);

        this.directions.clear();
    }

    public long getNodeId() {
        return this.nodeId;
    }

    public void setNodeCross(NodeVo node) {
        if (node != null && this.node != null) {
            if (this.node.getNodeId() == node.getNodeId()) {
                return;
            }
        }
        this.node = node;
        init();
    }

    @SuppressLint("ObsoleteSdkInt")
    public void updateSignal(CpuNodeStatusDTO status, int directionCode) {
        if (this.node == null || this.nodeId != status.getA()) {
            return;
        }

        this.tvCycle.setText(String.valueOf(status.getC()));
        this.tvTime.setText(status.getB());

        this.cpuControl.updateStatus(status.getD());
        if (this.cpuControl.isUpdate) {
            for (int ii = 0; ii < CpuControl.MAX_STATUS; ii++) {

                this.tvStatus[ii].setTextColor(this.cpuControl.status[ii] ? this.activeTextColor : this.normalTextColor);

                if (this.tvStatus[ii].getAnimation() != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                        this.tvStatus[ii].getAnimation().cancel();
                    }
                    this.tvStatus[ii].clearAnimation();
                    this.tvStatus[ii].setAnimation(null);
                }
                if (ii == 3) {
                    this.tvStatus[ii].setBackgroundResource(this.cpuControl.status[ii] ? R.drawable.rect_active : R.drawable.rect_border);  // 점멸
                }
                else {
                    this.tvStatus[ii].setBackgroundResource(this.cpuControl.status[ii] ? R.drawable.rect_active : R.drawable.rect_none);
                }
                if (this.cpuControl.status[ii]) {
                    Animation animation = AnimationUtils.loadAnimation(this.context, R.anim.blink);
                    this.tvStatus[ii].startAnimation(animation);
                }
            }
        }

/*
        //getResources().getIdentifier("가져올 ID" + i(숫자), "id", "패키지이름");
        //액티비티에서 사용할 때
        getResources().getIdentifier("negBestCommId" + i, "id", this.getPackageName());
        //프래그먼트에서 사용할 때
        getResources().getIdentifier("negBestCommId" + i, "id", getActivity().getPackageName());
*/

        //
        // 방향코드에 맞는 데이터 표출
        for (int ii = 0; ii < status.getG().size(); ii++) {

            SignalItem item = this.directions.get(status.getG().get(ii).getH());
            if (item == null) {
                item = new SignalItem();
                item.setDirection(status.getG().get(ii).getH());
                this.directions.put(status.getG().get(ii).getH(), item);
            }
            item.setStatus(status.getG().get(ii));
        }

        Object[] mapkey = this.directions.keySet().toArray();
        Arrays.sort(mapkey);
        ArrayList<SignalItem> list = new ArrayList<>();
        for (Object nKey : mapkey)
        {
            list.add(this.directions.get(nKey));
        }
        this.UserSignalItemAdapter.setItems(list);
    }

}
