package com.unibuy.smartdevice.ui.devs.electric;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.unibuy.smartdevice.AppCompatActivityAbstract;
import com.unibuy.smartdevice.MyApp;
import com.unibuy.smartdevice.database.SlotsDao;
import com.unibuy.smartdevice.databinding.ActivityElectricSlotListBinding;
import com.unibuy.smartdevice.devices.SlotField;
import com.unibuy.smartdevice.exception.LogsParseException;
import com.unibuy.smartdevice.exception.LogsSettingEmptyException;
import com.unibuy.smartdevice.external.HttpAPI;
import com.unibuy.smartdevice.structure.ProductStructure;
import com.unibuy.smartdevice.structure.SlotStructure;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.ToastHandlerMain;
import com.unibuy.smartdevice.ui.devs.vmc.VmcSlotListActivity;
import com.unibuy.smartdevice.utils.LanguageHelper;

public class ElectricSlotListActivity extends AppCompatActivityAbstract {
    private ActivityElectricSlotListBinding binding;
    private ActivityResultLauncher<Intent> resultLauncher;
    private RecyclerElectricSlotListAdpter recyclerElectricSlotListAdpter;
    private HttpAPI httpAPI;

    @Override
    protected Context setCtx() {
        return this;
    }

    @Override
    protected Class<?> setCls() {
        return getClass();
    }

    @Override
    protected HandlerMain setHandlerMain() {
        return new ToastHandlerMain(getCtx(), getLogs());
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
        LanguageHelper.applySavedLanguage(this);

        binding = ActivityElectricSlotListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        httpAPI = new HttpAPI(getHandlerMain());
        resultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult o) {
                    if (o.getResultCode() == RESULT_OK && o.getData() != null) {
                        int position = o.getData().getIntExtra("position", 0);
                        int slot = MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).get(position).getSlot();
                        String productId = o.getData().getStringExtra("product_id");
                        getLogs().info("接收到回傳值:" + position + "," + slot + "," + productId);
                        for(ProductStructure product: MyApp.getInstance().getProductList()) {
                            if (product.getProductID().equals(productId)) {
                                MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).set(position, new SlotStructure(SlotField.ELECTRIC.getField(), slot, product, 999));
                                break;
                            }
                        }
                        recyclerElectricSlotListAdpter.notifyItemChanged(position);
                    }
                }
            }
        );

//        MyApplication.getInstance().initialSlotData();

        recyclerElectricSlotListAdpter = new RecyclerElectricSlotListAdpter(this, resultLauncher, MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()));
        binding.recyclerSlotList.setAdapter(recyclerElectricSlotListAdpter);
        binding.recyclerSlotList.setLayoutManager(new LinearLayoutManager(this));

//        dataShow();

        binding.buttonBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                updateSlotListNum();
                finish();
            }
        });

        binding.buttonReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearData();
                saveData();
                dataShow();
            }
        });

        binding.buttonGotoVmcSlotList.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveData();
                gotoVmcAcitvity();
            }
        });
    }

    public void gotoVmcAcitvity() {
        startActivity(new Intent(this, VmcSlotListActivity.class));
        finish();
    }

    private void saveData() {
        SlotsDao slotsDao = new SlotsDao(this);
        slotsDao.deleteAll();
        slotsDao.insertAll(MyApp.getInstance().getSlotMap());
        slotsDao.close();
        getLogs().info("save count:"+ MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).size());
    }

    public void clearData() {
        SlotsDao slotsDao = new SlotsDao(this);
        slotsDao.deleteAll();
        slotsDao.close();
        int slotListSize = MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).size();
        MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).clear();
        if (slotListSize > 0) {
            recyclerElectricSlotListAdpter.notifyItemRangeRemoved(0, slotListSize);
        }
        if (MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).isEmpty()) {
            for (int i = 1; i <= 10; i++) {
                MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).add(new SlotStructure(SlotField.ELECTRIC.getField(), i,
                        new ProductStructure("?", "", "", 0, 0, 0, 0, "", "","",""),
                        0));
            }
            getLogs().info(SlotField.ELECTRIC.getField() + " count:"+ MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).size());
        }
    }

    private void testData() {
        for(int i=0;i<=10;i++) {
            MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).add(new SlotStructure(SlotField.ELECTRIC.getField(), i,
                new ProductStructure(
                "1000",
                "gg1.png",
                "測試小精靈"+i,
                100+1,
                100+2,
                100+3,
                8,
                        "",
                        "",
                        "",
                        ""
                ), 3));
        }
    }

    public void dataShow() {
        getLogs().info("recycler data count:"+this.recyclerElectricSlotListAdpter.getItemCount());
        recyclerElectricSlotListAdpter.notifyItemInserted(MyApp.getInstance().getSlotList(SlotField.ELECTRIC.getField()).size() -1);
    }

    public void updateSlotListNum(){
        try {
            MyApp.getInstance().getReportSlotListStructure().setAccount(MyApp.getInstance().getSuAccess());
            MyApp.getInstance().getReportSlotListStructure().setVmctype("U4");
            httpAPI.reportSlotList(MyApp.getInstance().getReportSlotListStructure());
        } catch (LogsParseException e) {
            throw new RuntimeException(e);
        } catch (LogsSettingEmptyException e) {
            throw new RuntimeException(e);
        }
    }
}