package com.grigowashere.aismap;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.grigowashere.aismap.data.Repository;
import com.grigowashere.aismap.data.entity.AISVesselEntity;

import java.util.ArrayList;
import java.util.List;

public class AisTargetsActivity extends AppCompatActivity implements AisTargetsAdapter.OnItemClickListener {

    private Repository repository;
    private RecyclerView recyclerView;
    private AisTargetsAdapter adapter;
    private android.os.Handler tickerHandler;
    private Runnable tickerRunnable;
    private android.widget.TextView textEmptyState;

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

        repository = new Repository(this);

        recyclerView = findViewById(R.id.recycler_ais_targets);
        textEmptyState = findViewById(R.id.text_empty_state);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new AisTargetsAdapter(new ArrayList<>(), this);
        recyclerView.setAdapter(adapter);

        repository.observeAllAIS().observe(this, new Observer<List<AISVesselEntity>>() {
            @Override
            public void onChanged(List<AISVesselEntity> entities) {
                // Стабильная сортировка по MMSI для предсказуемого порядка
                if (entities != null) {
                    java.util.Collections.sort(entities, (a, b) -> a.mmsi.compareTo(b.mmsi));
                }
                adapter.submitList(entities);
                
                // Показываем/скрываем сообщение о пустом состоянии
                if (entities == null || entities.isEmpty()) {
                    textEmptyState.setVisibility(android.view.View.VISIBLE);
                    recyclerView.setVisibility(android.view.View.GONE);
                } else {
                    textEmptyState.setVisibility(android.view.View.GONE);
                    recyclerView.setVisibility(android.view.View.VISIBLE);
                }
            }
        });

        // Тикер для обновления поля "N сек назад"
        tickerHandler = new android.os.Handler(android.os.Looper.getMainLooper());
        tickerRunnable = new Runnable() {
            @Override
            public void run() {
                try {
                    // Обновляем только элементы с данными, чтобы избежать мигания
                    int itemCount = adapter.getItemCount();
                    for (int i = 0; i < itemCount; i++) {
                        adapter.notifyItemChanged(i, "time_update");
                    }
                } finally {
                    tickerHandler.postDelayed(this, 1000);
                }
            }
        };
        tickerHandler.postDelayed(tickerRunnable, 1000);
    }

    @Override
    public void onMarinetrafficClick(String mmsi) {
        String url = "https://www.marinetraffic.com/ru/ais/details/ships/mmsi:" + mmsi;
        Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        startActivity(browserIntent);
    }

    @Override
    public void onCenterOnMapClick(String mmsi, double lat, double lon) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("center_mmsi", mmsi);
        intent.putExtra("center_lat", lat);
        intent.putExtra("center_lon", lon);
        startActivity(intent);
        finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (tickerHandler != null && tickerRunnable != null) {
            tickerHandler.removeCallbacks(tickerRunnable);
        }
    }
}


