package com.fusi24.entryPermitScanner.ui.home;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.annimon.stream.Collectors;
import com.annimon.stream.Stream;
import com.fusi24.entryPermitScanner.BuildConfig;
import com.fusi24.entryPermitScanner.R;
import com.fusi24.entryPermitScanner.SplashScreenActivity;
import com.fusi24.entryPermitScanner.adapter.SiteAdapter;
import com.fusi24.entryPermitScanner.adapter.StatusScanAdapter;
import com.fusi24.entryPermitScanner.base.BaseActivity;
import com.fusi24.entryPermitScanner.config.Constant;
import com.fusi24.entryPermitScanner.data.entity.DataDetail;
import com.fusi24.entryPermitScanner.data.entity.DataDevice;
import com.fusi24.entryPermitScanner.data.entity.DataEntryPermit;
import com.fusi24.entryPermitScanner.data.entity.DataSite;
import com.fusi24.entryPermitScanner.databinding.ActivityHomeBinding;
import com.fusi24.entryPermitScanner.ui.ScanActivity;
import com.fusi24.entryPermitScanner.ui.setting.SettingActivity;
import com.google.gson.Gson;

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

import timber.log.Timber;

public class HomeActivity extends BaseActivity implements HomeView, StatusScanAdapter.OnItemSelected {

    private DataEntryPermit dataEntryPermit;
    private List<DataEntryPermit> entryPermitList;
    private List<DataDetail> statusScanList;
    private ActivityHomeBinding binding;
    private HomePresenter presenter;
    private StatusScanAdapter scanAdapter;
    private SiteAdapter siteAdapter;
    private Integer idCheckType = null;
    private String idDevice, checkTypeName, uniqueId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityHomeBinding.inflate(getLayoutInflater());
        View view = binding.getRoot();
        setContentView(view);

        Toolbar toolbar = findViewById(R.id.toolbar);
        TextView toolbarTitle = findViewById(R.id.toolbar_text);

        if (toolbarTitle != null && toolbar != null) {
            toolbarTitle.setText(getString(R.string.app_name));
            setSupportActionBar(toolbar);
        }

        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayShowTitleEnabled(false);
        }

        presenter = new HomePresenter(getManager(), getAndroidScheduler(), getProcessScheduler());
        presenter.attachView(this);

        initView();
        getDataDeviceId();
        loadingData();
        getDataFromService();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.app_version)
                .setEnabled(false)
                .setTitle(BuildConfig.VERSION_NAME);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        if (item.getItemId() == R.id.action_setting) {
            startActivity(new Intent(this, SettingActivity.class));
            return true;
        }

        if (item.getItemId() == R.id.action_logout) {
            getSessionManager().clearData();
            startActivity(new Intent(this, SplashScreenActivity.class));
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadingData();
        initEvent();
    }

    private void initView() {
        binding.refresh.setRefreshing(false);
        ActivityCompat.requestPermissions(this, Constant.PERMISSIONS_RFID, 1000);

        entryPermitList = new ArrayList<>();
        statusScanList = new ArrayList<>();

        scanAdapter = new StatusScanAdapter(this, this);
        binding.rvStatusScan.setLayoutManager(new LinearLayoutManager(this));
        binding.rvStatusScan.setItemAnimator(new DefaultItemAnimator());
        binding.rvStatusScan.setAdapter(scanAdapter);

        siteAdapter = new SiteAdapter(this);
        binding.rvSite.setLayoutManager(new LinearLayoutManager(this));
        binding.rvSite.setItemAnimator(new DefaultItemAnimator());
        binding.rvSite.setAdapter(siteAdapter);
    }

    @SuppressLint("SetTextI18n")
    private void loadingData() {
        // Build.DISPLAY is different
        idDevice = "RFID" + "-" + Build.ID + "-" + uniqueId;
        binding.tvRfidGunId.setText(idDevice);
        binding.tvRfidCardNumber.setText(getSessionManager().getUserRfidNumber());
        binding.tvEmployeeName.setText(getSessionManager().getEmployeeName());
        binding.tvGateName.setText(getSessionManager().getGate());

        if (getSessionManager().getSiteList() != null) {
            siteAdapter.updateSiteList(getSessionManager().getSiteList());
            siteAdapter.notifyDataSetChanged();
        }

        if (getSessionManager().getPermitList() != null) {
            entryPermitList.clear();
            entryPermitList.addAll(getSessionManager().getPermitList());
        }
        setDataPermit();

        Gson gson = new Gson();
        System.out.println("Developer Gate : " + gson.toJson(getSessionManager().getGate()));
        System.out.println("Developer Site : " + gson.toJson(getSessionManager().getSiteList()));
        System.out.println("Developer Permit : " + gson.toJson(getSessionManager().getPermitList()));
    }

    private void getDataFromService(){
        presenter.getEntryPermit();
        presenter.getStatusScan();
        presenter.getDataDevice(idDevice);
    }

    private void initEvent(){

        binding.spinnerPermit.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                dataEntryPermit = (DataEntryPermit) parent.getItemAtPosition(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                dataEntryPermit = (DataEntryPermit) parent.getSelectedItem();
            }
        });

        binding.btnScan.setOnClickListener(v -> {

            if (binding.spinnerPermit.getSelectedItem() == null){
                Toast.makeText(this, "Data Permit Belum Terpilih", Toast.LENGTH_SHORT).show();
                return;
            }

            if (idCheckType == null){
                Toast.makeText(this, "Status Scan Belum Terpilih", Toast.LENGTH_SHORT).show();
                return;
            }

            Intent intent = new Intent(this, ScanActivity.class);
            intent.putExtra(ScanActivity.ID_PERMIT, String.valueOf(dataEntryPermit.getId()));
            intent.putExtra(ScanActivity.ID_DEVICE, idDevice);
            intent.putExtra(ScanActivity.ID_CHECK_TYPE, idCheckType);
            intent.putExtra(ScanActivity.CHECK_TYPE_NAME, checkTypeName);
            startActivity(intent);
        });

        binding.refresh.setOnRefreshListener(this::getDataFromService);

    }

    @Override
    public void onSelected(DataDetail detail) {
        idCheckType = detail.getId();
        checkTypeName = detail.getName();
    }

    @Override
    public void showDataPermit(List<DataEntryPermit> dataEntryPermitList) {
        binding.refresh.setRefreshing(false);
        getSessionManager().setPermitList(dataEntryPermitList);
    }

    @Override
    public void showDataStatusScan(List<DataDetail> dataStatusScanList) {
        binding.refresh.setRefreshing(false);
        statusScanList.clear();
        statusScanList.addAll(dataStatusScanList);
        scanAdapter.updateDetailList(statusScanList);
        scanAdapter.notifyDataSetChanged();
        setDataStatusScan(dataStatusScanList.size());
    }

    @Override
    public void showDataDevice(List<DataDevice> dataDevices) {
        // If data empty clear session
        if (dataDevices.isEmpty()){
            List<DataSite> siteList = new ArrayList<>();
            getSessionManager().setSiteList(siteList);
            getSessionManager().setGate("");
        } else {
            getSessionManager().setGate(dataDevices.get(0).getGate().getName()); // Data Gate
            getSessionManager().setSiteList(Stream.of(dataDevices.get(0).getGate().getSites()) // Data Site
                    .filter(DataSite::getActive)
                    .sortBy(DataSite::getId).toList());
        }
        binding.refresh.setRefreshing(false);
        loadingData();
    }

    private void setDataPermit(){
        ArrayAdapter<DataEntryPermit> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,
                Stream.of(entryPermitList).filter(DataEntryPermit::getActive).collect(Collectors.toList()));
        binding.spinnerPermit.setAdapter(adapter);
    }

    private void setDataStatusScan(Integer size){
        if (size <= 2){
            binding.swStatusScan.setVisibility(View.VISIBLE);
            binding.rvStatusScan.setVisibility(View.GONE);
        } else {
            binding.swStatusScan.setVisibility(View.GONE);
            binding.rvStatusScan.setVisibility(View.VISIBLE);
        }

        // Inisiasi pertama saat muncul halaman default true
        idCheckType = statusScanList.get(0).getId(); // <-- Check In Code (649)
        checkTypeName = statusScanList.get(0).getName(); // <-- Check In Name

        binding.swStatusScan.setLabelOn(statusScanList.get(0).getName());
        binding.swStatusScan.setLabelOff(statusScanList.get(1).getName());

        binding.swStatusScan.setOnToggledListener((toggleableView, isOn) -> {
            if (isOn){
                idCheckType = statusScanList.get(0).getId();
                checkTypeName = statusScanList.get(0).getName();
            } else {
                idCheckType = statusScanList.get(1).getId();
                checkTypeName = statusScanList.get(1).getName();
            }
        });
    }


    @SuppressLint("HardwareIds")
    private void getDataDeviceId(){
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, Constant.PERMISSIONS_RFID, 1000);
            return;
        }
        TelephonyManager mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String imsi = "";
        String imei = "";
        if (mTelephonyMgr != null) {
            imsi = mTelephonyMgr.getSubscriberId();
            imei = mTelephonyMgr.getDeviceId();
        }
        String uniqueId = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        System.out.println("DEVELOPER 1 : " + imsi);
        System.out.println("DEVELOPER 2 : " + imei);
        System.out.println("DEVELOPER 3 : " + uniqueId);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
            this.uniqueId = uniqueId;
        } else {
            if (mTelephonyMgr != null) {
                if (mTelephonyMgr.getDeviceId() != null){
                    this.uniqueId = imei;
                } else {
                    this.uniqueId = uniqueId;
                }
            }
        }
    }

    @Override
    public void showError(Throwable e) {
        binding.refresh.setRefreshing(false);
        Toast.makeText(HomeActivity.this, "Failed get data, try refresh again", Toast.LENGTH_SHORT).show();
        Timber.i("DEVELOPER : %s", e.getMessage());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        binding = null;
    }
}
