package com.example.kingway.ptt;

import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.stand.standapp.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;

public class pttActivity extends AppCompatActivity {
    private Button pttBtn;
    private AutoCompleteTextView etIp, etAccount, etPassword, etGroupId;
    private static final String PREFS_NAME = "ptt_history";
    private static final String KEY_IP_HISTORY = "ip_history";
    private static final String KEY_ACCOUNT_HISTORY = "account_history";
    private static final String KEY_PASSWORD_HISTORY = "password_history";
    private static final String KEY_GROUP_HISTORY = "group_history";
    private static final String SEPARATOR = ",";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ptt);

        etIp = findViewById(R.id.etIp);
        etAccount = findViewById(R.id.etAccount);
        etPassword = findViewById(R.id.etPassword);
        etGroupId = findViewById(R.id.etGroupId);

        loadHistory();

        pttBtn = (Button) findViewById(R.id.pttBtn);
        XXPermissions.with(this)
                .permission(Permission.RECORD_AUDIO)
                .request(null);
        pttBtn.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    pttBtn.setBackgroundColor(Color.RED);
                    SendAtUtil.speakPlay();
                } else if (motionEvent.getAction() == MotionEvent.ACTION_UP) {
                    pttBtn.setBackgroundColor(Color.BLUE);
                    SendAtUtil.speakRelease();
                }
                return false;
            }
        });

        findViewById(R.id.login).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.toLogin("gzzdweb01", "123456", "61.243.1.123", 1, 1);
            }
        });

        findViewById(R.id.btnCustomLogin).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ip = etIp.getText().toString().trim();
                String account = etAccount.getText().toString().trim();
                String password = etPassword.getText().toString().trim();
                String groupId = etGroupId.getText().toString().trim();

                if (ip.isEmpty() || account.isEmpty() || password.isEmpty() || groupId.isEmpty()) {
                    Toast.makeText(pttActivity.this, "请填写所有字段", Toast.LENGTH_SHORT).show();
                    return;
                }

                saveToHistory(ip, account, password, groupId);
                SendAtUtil.toLogin(account, password, ip, 1, 1);
            }
        });

        findViewById(R.id.login1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.toLogin("test004", "123456", "220.154.131.231", 1, 1);
            }
        });

        findViewById(R.id.button2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.getGroupInfo();
            }
        });

        findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.getGroupMemberInfo("00000001");
            }
        });

        findViewById(R.id.btnJumpGroup).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.jumpGroup("00000001");
            }
        });

        findViewById(R.id.btnCancel1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.toCancelLogin();
            }
        });

        findViewById(R.id.btnCancel2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SendAtUtil.toLogout();
            }
        });
    }

    private void loadHistory() {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        setupAdapter(etIp, prefs.getString(KEY_IP_HISTORY, ""));
        setupAdapter(etAccount, prefs.getString(KEY_ACCOUNT_HISTORY, ""));
        setupAdapter(etPassword, prefs.getString(KEY_PASSWORD_HISTORY, ""));
        setupAdapter(etGroupId, prefs.getString(KEY_GROUP_HISTORY, ""));
    }

    private void setupAdapter(AutoCompleteTextView view, String historyStr) {
        List<String> items = new ArrayList<>();
        if (!historyStr.isEmpty()) {
            items.addAll(Arrays.asList(historyStr.split(SEPARATOR)));
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                android.R.layout.simple_dropdown_item_1line, items);
        view.setAdapter(adapter);
        view.setThreshold(1);
    }

    private void saveToHistory(String ip, String account, String password, String groupId) {
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString(KEY_IP_HISTORY, addToHistory(prefs.getString(KEY_IP_HISTORY, ""), ip));
        editor.putString(KEY_ACCOUNT_HISTORY, addToHistory(prefs.getString(KEY_ACCOUNT_HISTORY, ""), account));
        editor.putString(KEY_PASSWORD_HISTORY, addToHistory(prefs.getString(KEY_PASSWORD_HISTORY, ""), password));
        editor.putString(KEY_GROUP_HISTORY, addToHistory(prefs.getString(KEY_GROUP_HISTORY, ""), groupId));
        editor.apply();
        loadHistory();
    }

    private String addToHistory(String existing, String newValue) {
        LinkedHashSet<String> set = new LinkedHashSet<>();
        if (!existing.isEmpty()) {
            set.addAll(Arrays.asList(existing.split(SEPARATOR)));
        }
        set.remove(newValue);
        set.add(newValue);
        return String.join(SEPARATOR, set);
    }
}
