package com.xypower.mpapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.xypower.common.JSONUtils;
import com.xypower.common.MicroPhotoContext;
import com.xypower.mpapp.databinding.ActivityChannelBinding;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;

import android.widget.AdapterView;

public class ChannelActivity extends AppCompatActivity {

    private ActivityChannelBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = ActivityChannelBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        binding.sensitivity.setOnFocusChangeListener(onFocusChangeListener);
        binding.exposuretime.setOnFocusChangeListener(onFocusChangeListener);

        int channel = binding.channels.getSelectedItemPosition();
        loadChannelParams(channel);

        binding.channels.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                int channel = i + 1;
                loadChannelParams(channel);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        binding.btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int channel = binding.channels.getSelectedItemPosition() + 1;
                saveChannelParams(channel);
                MicroPhotoService.updateConfigs(ChannelActivity.this.getApplicationContext());
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        ChannelActivity.this.finish();
                    }
                }, 200);

            }
        });

        /*
        binding.btnNightMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.btnNightMode.isChecked() && binding.btnHdrMode.isChecked()) {
                    binding.btnHdrMode.setChecked(false);
                }
            }
        });

        binding.btnHdrMode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (binding.btnHdrMode.isChecked() && binding.btnNightMode.isChecked()) {
                    binding.btnNightMode.setChecked(false);
                }
            }
        });
         */
    }

    private View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View view, boolean b) {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // TODO Auto-generated method stub
        MenuInflater mMenuInflater = new MenuInflater(this);
        mMenuInflater.inflate(R.menu.menu_channel, menu);
        //return true;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                // todo: goto back activity from here

                finish();
                return true;

            case R.id.action_save:
                // todo: goto back activity from here
                int channel = binding.channels.getSelectedItemPosition() + 1;
                saveChannelParams(channel);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    protected void loadChannelParams(int channel) {

        binding.btnAutoExplosure.setChecked(true);
        binding.btnAutoFocus.setChecked(true);
        // binding.btnHdrMode.setChecked(true);
        binding.exposuretime.setText("0");
        binding.sensitivity.setText("0");

        String appPath = MicroPhotoContext.buildAppDir(getApplicationContext());

        try {
            String path = appPath + "data/channels/" + String.valueOf(channel) + ".json";

            JSONObject jsonObject = JSONUtils.loadJson(path);
            if (jsonObject == null) {
                jsonObject = new JSONObject();
            }
            binding.btnUsbCamera.setChecked(jsonObject.optInt("usbCamera", 0) == 1);
            binding.btnAutoExplosure.setChecked(jsonObject.optInt("autoExposure", 1) == 1);
            binding.btnAutoFocus.setChecked(jsonObject.optInt("autoFocus", 1) == 1);
            binding.ldrEnabled.setChecked(jsonObject.optInt("ldrEnabled", 0) == 1);
            // binding.btnHdrMode.setChecked(jsonObject.optInt("hdrMode", 0) == 1);
            // binding.btnNightMode.setChecked(jsonObject.optInt("nightMode", 0) == 1);
            int sceneMode = jsonObject.optInt("sceneMode", 0);
            String sceneModeText = Integer.toString(sceneMode) + " ";
            for (int idx = 0; idx < binding.sceneModes.getCount(); idx++) {
                String text = (String)binding.sceneModes.getItemAtPosition(idx);
                if (text.indexOf(sceneModeText) == 0) {
                    binding.sceneModes.setSelection(idx);
                    break;
                }
            }
            int requestTemplate = jsonObject.optInt("requestTemplate", 2);
            String requestTemplateText = Integer.toString(requestTemplate) + "-";
            for (int idx = 0; idx < binding.requestTemplates.getCount(); idx++) {
                String text = (String)binding.requestTemplates.getItemAtPosition(idx);
                if (text.startsWith(requestTemplateText)) {
                    binding.requestTemplates.setSelection(idx);
                    break;
                }
            }
            binding.exposuretime.setText(Integer.toString(jsonObject.optInt("exposureTime", 0)));
            binding.sensitivity.setText(Integer.toString(jsonObject.optInt("sensitivity", 0)));
            binding.btnZoom.setChecked(jsonObject.optInt("zoom", 0) == 1);
            if (jsonObject.has("compensation")) {
                binding.compensation.setText(Integer.toString(jsonObject.optInt("compensation", 0)));
            } else {
                binding.compensation.setText("");
            }

            NumberFormat nf = NumberFormat.getNumberInstance();
            nf.setMaximumFractionDigits(1);
            nf.setMinimumFractionDigits(1);
            String zoomRatio = nf.format(jsonObject.optDouble("zoomRatio", 1.0));
            for (int idx = 0; idx < binding.zoomRatio.getCount(); idx++) {
                String text = (String)binding.zoomRatio.getItemAtPosition(idx);
                if (TextUtils.equals(text, zoomRatio)) {
                    binding.zoomRatio.setSelection(idx);
                    break;
                }
            }
            binding.orientations.setSelection(jsonObject.optInt("orientation", 0));
            binding.recognization.setSelection(jsonObject.optInt("recognization", 0));
            if (jsonObject.has("cameraId")) {
                binding.cameraId.setText(Integer.toString(jsonObject.optInt("cameraId", channel - 1)));
            } else {
                binding.cameraId.setText("");
            }

            if (jsonObject.has("wait3ALocked")) {
                binding.btnWait3ALocked.setText(Integer.toString(jsonObject.optInt("wait3ALocked")));
            } else {
                binding.btnWait3ALocked.setText("");
            }

            if (jsonObject.has("resolutionCX")) {
                binding.resolutionCX.setText(Integer.toString(jsonObject.optInt("resolutionCX")));
            } else {
                binding.resolutionCX.setText("");
            }
            if (jsonObject.has("resolutionCY")) {
                binding.resolutionCY.setText(Integer.toString(jsonObject.optInt("resolutionCY")));
            } else {
                binding.resolutionCY.setText("");
            }
            if (jsonObject.has("quality")) {
                binding.quality.setText(Integer.toString(jsonObject.optInt("quality")));
            } else {
                binding.quality.setText("");
            }
            if (jsonObject.has("videoCX")) {
                binding.videoCX.setText(Integer.toString(jsonObject.optInt("videoCX")));
            } else {
                binding.videoCX.setText("");
            }
            if (jsonObject.has("videoCY")) {
                binding.videoCY.setText(Integer.toString(jsonObject.optInt("videoCY")));
            } else {
                binding.videoCY.setText("");
            }
            if (jsonObject.has("videoDuration")) {
                binding.videoDuration.setText(Integer.toString(jsonObject.optInt("videoDuration")));
            } else {
                binding.videoDuration.setText("");
            }

            JSONObject osdJsonObj = jsonObject.optJSONObject("osd");
            if (osdJsonObj != null) {
                binding.osdLeftTop.setText(osdJsonObj.optString("leftTop", ""));
                binding.osdRightTop.setText(osdJsonObj.optString("rightTop", ""));
                binding.osdRightBottom.setText(osdJsonObj.optString("rightBottom", ""));
                binding.osdLeftBottom.setText(osdJsonObj.optString("leftBottom", ""));
            } else {
                binding.osdLeftTop.setText("");
                binding.osdRightTop.setText("");
                binding.osdRightBottom.setText("");
                binding.osdLeftBottom.setText("");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveChannelParams(int channel) {

        JSONObject jsonObject = null;
        String appPath = MicroPhotoContext.buildAppDir(this.getApplicationContext());
        String dataPath = appPath + "data/channels/";
        String filePath = dataPath + String.valueOf(channel) + ".json";

        jsonObject = JSONUtils.loadJson(filePath);

        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }

        try {
            jsonObject.put("usbCamera", binding.btnUsbCamera.isChecked() ? 1 : 0);
            jsonObject.put("autoExposure", binding.btnAutoExplosure.isChecked() ? 1 : 0);
            jsonObject.put("autoFocus", binding.btnAutoFocus.isChecked() ? 1 : 0);
            jsonObject.put("wait3ALocked", Integer.parseInt(binding.btnWait3ALocked.getText().toString()));
            jsonObject.put("ldrEnabled", binding.ldrEnabled.isChecked() ? 1 : 0);
            // jsonObject.put("hdrMode", binding.btnHdrMode.isChecked() ? 1 : 0);
            // jsonObject.put("nightMode", binding.btnNightMode.isChecked() ? 1 : 0);
            int sceneMode = 0;
            String sceneModeText = (String)binding.sceneModes.getSelectedItem();
            sceneModeText = sceneModeText.substring(0, sceneModeText.indexOf(" -"));
            sceneMode = Integer.parseInt(sceneModeText);
            jsonObject.put("sceneMode", sceneMode);

            int requestTemplate = 2;
            String requestTemplateText = (String)binding.requestTemplates.getSelectedItem();
            requestTemplateText = requestTemplateText.substring(0, requestTemplateText.indexOf("-"));
            requestTemplate = Integer.parseInt(requestTemplateText);
            jsonObject.put("requestTemplate", requestTemplate);

            jsonObject.put("exposureTime", Integer.parseInt(binding.exposuretime.getText().toString()));
            jsonObject.put("sensitivity", Integer.parseInt(binding.sensitivity.getText().toString()));
            jsonObject.put("zoom", binding.btnZoom.isChecked() ? 1 : 0);
            jsonObject.put("orientation", binding.orientations.getSelectedItemPosition());
            jsonObject.put("recognization", binding.recognization.getSelectedItemPosition());
            // binding.cameraId.setText(jsonObject.optString("cameraId", ""));
            if (!TextUtils.isEmpty(binding.cameraId.getText().toString())) {
                jsonObject.put("cameraId", Integer.parseInt(binding.cameraId.getText().toString()));
            } else {
                jsonObject.remove("cameraId");
            }
            if (binding.zoomRatio.getSelectedItemPosition() >= 0) {
                jsonObject.put("zoomRatio", Float.valueOf(binding.zoomRatio.getSelectedItem().toString()));
            } else {
                jsonObject.put("zoomRatio", 0f);
            }
            String text = binding.compensation.getText().toString();
            if (TextUtils.isEmpty(text)) {
                jsonObject.remove("compensation");
            } else {
                jsonObject.put("compensation", Integer.parseInt(text));
            }
            if (!TextUtils.isEmpty(binding.resolutionCX.getText().toString())) {
                jsonObject.put("resolutionCX", Integer.parseInt(binding.resolutionCX.getText().toString()));
            } else {
                jsonObject.remove("resolutionCX");
            }
            if (!TextUtils.isEmpty(binding.resolutionCY.getText().toString())) {
                jsonObject.put("resolutionCY", Integer.parseInt(binding.resolutionCY.getText().toString()));
            } else {
                jsonObject.remove("resolutionCY");
            }
            if (!TextUtils.isEmpty(binding.quality.getText().toString())) {
                jsonObject.put("quality", Integer.parseInt(binding.quality.getText().toString()));
            } else {
                jsonObject.remove("quality");
            }

            if (!TextUtils.isEmpty(binding.videoCX.getText().toString())) {
                jsonObject.put("videoCX", Integer.parseInt(binding.videoCX.getText().toString()));
            } else {
                jsonObject.remove("videoCX");
            }
            if (!TextUtils.isEmpty(binding.videoCY.getText().toString())) {
                jsonObject.put("videoCY", Integer.parseInt(binding.videoCY.getText().toString()));
            } else {
                jsonObject.remove("videoCY");
            }
            if (!TextUtils.isEmpty(binding.videoDuration.getText().toString())) {
                jsonObject.put("videoDuration", Integer.parseInt(binding.videoDuration.getText().toString()));
            } else {
                jsonObject.remove("videoDuration");
            }

            JSONObject osdJsonObj = jsonObject.optJSONObject("osd");
            if (osdJsonObj == null) {
                osdJsonObj = jsonObject.put("osd", new JSONObject());
            }

            osdJsonObj.put("leftTop", binding.osdLeftTop.getText().toString());
            osdJsonObj.put("rightTop", binding.osdRightTop.getText().toString());
            osdJsonObj.put("rightBottom", binding.osdRightBottom.getText().toString());
            osdJsonObj.put("leftBottom", binding.osdLeftBottom.getText().toString());

        } catch (JSONException ex) {
        }

        try {
            File dataPathFile = new File(dataPath);
            if (!dataPathFile.exists()) {
                dataPathFile.mkdirs();
            }
            JSONUtils.saveJson(filePath, jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}