package com.example.scoutingapp;

import android.content.Context;
import android.content.Intent;

import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;

public class MainActivity extends AppCompatActivity {
    public static MatchData matchData = new MatchData();
    private EditText matchNumber;
    private RadioButton r1Button, r2Button, r3Button, b1Button, b2Button, b3Button;
    private SharedPreferences sharedPreferences;

    private String red1, red2, red3, blue1, blue2, blue3;
    InputStream stream;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        if (isNetworkConnected()){
            Toast.makeText(this, getString(R.string.online_mode_toast), Toast.LENGTH_SHORT).show();
        } else {
            makeOffline();
        }
        sharedPreferences = getSharedPreferences("MySettings", MODE_PRIVATE);
        String EventText = sharedPreferences.getString("MatchText", "");
        String NameText = sharedPreferences.getString("NameText", "");
        //EditText scoutNameTextBox = (EditText) findViewById(R.id.scoutNameText);
        matchNumber = findViewById(R.id.Match);

        if (matchData.getMatchNumber() == 0) {
            matchData.setMatchNumber(1);
        }

        matchNumber.setText(String.valueOf(matchData.getMatchNumber()));



        Button nextButton = (Button) findViewById(R.id.ButtonNext);
        Button Offline = (Button) findViewById(R.id.Offline);
        Button Submit = (Button) findViewById(R.id.buttonSubmit);
        Button Practice = (Button) findViewById(R.id.Practice);

        nextButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                matchData.setScoutName(NameText);
                matchData.setEventName(EventText);

                if (matchData.getEventName().isEmpty() ||
                        matchData.getMatchNumber() == 0 ||
                        matchData.getTeamNumber().equals("0000") ||
                        matchData.getScoutName().isEmpty() ||
                        matchData.getScoutName().equals("NO NAME PROVIDED"))
                {            Toast.makeText(
                        getApplicationContext(),
                        getString(R.string.fill_everything_error),
                        Toast.LENGTH_SHORT
                ).show();
                } else
                    makeIntent();
                }

        });
        Submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isNetworkConnected()) {
                    String csvFileString = "offlineData.csv";
                    Submit submit = new Submit();
                    //Writes data to file to make google sheet read it as a list
                    File csvFilefile = new File(getFilesDir(), csvFileString);
                    List<List<Object>> data = submit.parseCSVToList(csvFilefile);
                    submit.parseCSVToList(csvFilefile);
                    //Uploads the Data to the Google sheet
                    submit.uploadSheets(MainActivity.this, csvFileString);
                } else {
                    Toast.makeText(MainActivity.this, getString(R.string.upload_failed_toast), Toast.LENGTH_SHORT).show();
                }
            }
        });


        Offline.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                matchData.setScoutName(NameText);
                matchData.setEventName(EventText);
                makeOffline();
            }

        });
        Practice.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                matchData.setScoutName(NameText);
                matchData.setTeamNumber("2648");
                matchData.setPractice(true);
                makeIntent();
            }
        });

        Button SettingsButton = (Button) findViewById(R.id.ButtonSettings);
        SettingsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                makeSettings();
            }
        });

        Button Sheet = (Button) findViewById(R.id.Sheet);
        Sheet.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://docs.google.com/spreadsheets/d/1ky5LBTpnEeBEEaaF7z6UWdh-E7YmOSeij4dYdR2PU4A/edit?gid=0#gid=0"));
                startActivity(browserIntent);
            }
        });

        r1Button = findViewById(R.id.red1Button);
        r2Button = findViewById(R.id.red2Button);
        r3Button = findViewById(R.id.red3Button);

        b1Button = findViewById(R.id.blue1Button);
        b2Button = findViewById(R.id.blue2Button);
        b3Button = findViewById(R.id.blue3Button);

        r1Button.setEnabled(false);
        r2Button.setEnabled(false);
        r3Button.setEnabled(false);

        b1Button.setEnabled(false);
        b2Button.setEnabled(false);
        b3Button.setEnabled(false);

        r1Button.setChecked(false);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
        PullData();

        matchNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_DONE) {
                    PullData();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    if (imm != null && v != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                    return true;
                }
                return false;
            }
        });
        r1Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                r1Button.setChecked(true);
                r2Button.setChecked(false);
                r3Button.setChecked(false);
                b1Button.setChecked(false);
                b2Button.setChecked(false);
                b3Button.setChecked(false);

                matchData.setBlueAlliance(false);
                matchData.setTeamNumber(red1);
            }
        });

        r2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                r1Button.setChecked(false);
                r2Button.setChecked(true);
                r3Button.setChecked(false);
                b1Button.setChecked(false);
                b2Button.setChecked(false);
                b3Button.setChecked(false);
                Log.d("TESTY", "GIT");
                matchData.setBlueAlliance(false);
                Log.d("TESTY", "GITTEST");
                matchData.setTeamNumber(red2);
                Log.d("TESTY", "GITTY");
            }
        });

        r3Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                r1Button.setChecked(false);
                r2Button.setChecked(false);
                r3Button.setChecked(true);
                b1Button.setChecked(false);
                b2Button.setChecked(false);
                b3Button.setChecked(false);

                matchData.setBlueAlliance(false);
                matchData.setTeamNumber(red3);
            }
        });

        b1Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                r1Button.setChecked(false);
                r2Button.setChecked(false);
                r3Button.setChecked(false);
                b1Button.setChecked(true);
                b2Button.setChecked(false);
                b3Button.setChecked(false);

                matchData.setBlueAlliance(true);
                matchData.setTeamNumber(blue1);
            }
        });

        b2Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                r1Button.setChecked(false);
                r2Button.setChecked(false);
                r3Button.setChecked(false);
                b1Button.setChecked(false);
                b2Button.setChecked(true);
                b3Button.setChecked(false);
                Log.d("TESTY", "GIT");
                matchData.setBlueAlliance(true);
                matchData.setTeamNumber(blue2);
            }
        });

        b3Button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                r1Button.setChecked(false);
                r2Button.setChecked(false);
                r3Button.setChecked(false);
                b1Button.setChecked(false);
                b2Button.setChecked(false);
                b3Button.setChecked(true);

                matchData.setBlueAlliance(true);
                matchData.setTeamNumber(blue3);
            }
        });
    }




    public InputStream getJSON(String path){

        InputStream stream = null;
        try{

            URL url = new URL(path);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("User-Agent", "TBA_API");
            connection.setRequestProperty("X-TBA-Auth-Key", "0zxxGYSvY7xI2onqcWg0NT0sEtmtR6hCpmYJ29nwfxvqrP3Mf1M3lRZO5x6Kc3kt");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("charset", "utf-8");
            connection.setUseCaches(false);

            stream = (InputStream)connection.getInputStream();
        }
        catch (Exception e){
            Log.d("test", "inside catch");
            e.printStackTrace();
        }
        return stream;
    }

    private void makeIntent() {
        Intent intent = new Intent(this, startingActivity.class);
        startActivity(intent);
    }

    private void makeOffline() {
        if (isNetworkConnected()){
            Intent intent = new Intent(this, OfflineActivity.class);
            startActivity(intent);
        } else {
            Intent intent = new Intent(this, OfflineActivity.class);
            startActivity(intent);
            finish();
        }
    }
    private void makeSettings() {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
    }
    private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
        }
        return false;
    }

    public void PullData() {
        if (matchNumber.getText().toString().isEmpty()) {
            Toast.makeText(getApplicationContext(), getString(R.string.match_number_required_toast), Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            matchData.setMatchNumber(Integer.parseInt(matchNumber.getText().toString()));
            String TBAURL = sharedPreferences.getString("TBAText", "");
            stream = getJSON(TBAURL + matchData.getMatchNumber());

            JsonElement jsonElement = JsonParser.parseReader(new InputStreamReader(stream));
            JsonObject teamsJSON = jsonElement.getAsJsonObject();

            // Blue Alliance Parsing
            JsonArray blueTeamsArray = teamsJSON.get("alliances").getAsJsonObject()
                    .get("blue").getAsJsonObject()
                    .get("team_keys").getAsJsonArray();

            blue1 = blueTeamsArray.get(0).getAsString().substring(3);
            blue2 = blueTeamsArray.get(1).getAsString().substring(3);
            blue3 = blueTeamsArray.get(2).getAsString().substring(3);

            // Red Alliance Parsing
            JsonArray redTeamsArray = teamsJSON.get("alliances").getAsJsonObject()
                    .get("red").getAsJsonObject()
                    .get("team_keys").getAsJsonArray();

            red1 = redTeamsArray.get(0).getAsString().substring(3);
            red2 = redTeamsArray.get(1).getAsString().substring(3);
            red3 = redTeamsArray.get(2).getAsString().substring(3);

            // Update UI
            r1Button.setText(red1);
            r2Button.setText(red2);
            r3Button.setText(red3);
            b1Button.setText(blue1);
            b2Button.setText(blue2);
            b3Button.setText(blue3);

            r1Button.setEnabled(true);
            r2Button.setEnabled(true);
            r3Button.setEnabled(true);
            b1Button.setEnabled(true);
            b2Button.setEnabled(true);
            b3Button.setEnabled(true);

        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), getString(R.string.invalid_match_error), Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }
}
