package epson.scan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.epson.iprint.shared.SharedParamScan;
import com.epson.lib.escani2.EscanI2Lib;
import com.epson.lib.escani2.ScanI2Params;

import java.io.IOException;
import java.util.Locale;

import epson.print.ActivityIACommon;
import epson.print.EPPrinterManager;
import epson.print.R;
import epson.scan.i2lib.I2ScanParamArbiter;
import epson.scan.i2lib.I2ScanParamManager;

public class I2ScanSettingActivity extends ActivityIACommon implements View.OnClickListener {
    private static final String PARAM_KEY_EXTERNAL_SCAN_PARAMS = "external-scan-params";
    private static final String PARAM_KEY_HIDE_COLOR_MODE = "hide-color-mode";
    private static final String PARAM_KEY_HIDE_RESOLUTION = "hide-resolution";
    private static final int REQUEST_CODE_CHANGE_ESC_I_VERSION = 100;
    private static final int REQUEST_CODE_SELECT_BRIGHTNESS = 8;
    private static final int REQUEST_CODE_SELECT_COLOR_MODE = 3;
    private static final int REQUEST_CODE_SELECT_DUPLEX = 5;
    private static final int REQUEST_CODE_SELECT_GAMMA = 6;
    private static final int REQUEST_CODE_SELECT_INPUT_UNIT = 1;
    private static final int REQUEST_CODE_SELECT_RESOLUTION = 4;
    private static final int REQUEST_CODE_SELECT_SCANNER = 7;
    private static final int REQUEST_CODE_SELECT_SCAN_SIZE = 2;
    private static final String RETURN_KEY_OLD_PREVIEW_VALID = "old-preview-valid";
    private View mBrightnessSeparator;
    private TextView mBrightnessText;
    private View mBrightnessViewGroup;
    private View mColorModeSeparator;
    private TextView mColorModeText;
    private View mColorModeViewGroup;
    private View mDuplexSeparator;
    private TextView mDuplexText;
    private View mDuplexViewGroup;
    private SharedParamScan mExternalScanParams;
    private TextView mGammaText;
    private View mGammaViewGroup;
    private boolean mHideColorMode;
    private boolean mHideResolutionMode;
    private I2ScanParamArbiter mI2ScanParamArbiter;
    private View mInputUnitSeparator;
    private TextView mInputUnitText;
    private View mInputUnitViewGroup;
    private ImageView mPrinterLocationIcon;
    private View mProgressBarLayout;
    private TextView mScanResolutionText;
    private View mScanResolutionViewGroup;
    private boolean mScanSizeSelected;
    private View mScanSizeSeparator;
    private TextView mScanSizeText;
    private View mScanSizeViewGroup;
    private boolean mScannerChanged;
    private TextView mScannerNameText;
    private View mScannerNameViewGroup;
    private ScannerPropertyWrapper mScannerPropertyWrapper;

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        mI2ScanParamArbiter = new I2ScanParamArbiter();
        mScanSizeSelected = false;
        setContentView(R.layout.activity_i2_scan_setting);
        setActionBar(R.string.str_lbl_title_scan_settings, true);
        mScannerNameViewGroup = findViewById(R.id.llScannerName);
        mScannerNameViewGroup.setOnClickListener(this);
        mScannerNameText = (TextView) findViewById(R.id.tvScannerName);
        mPrinterLocationIcon = (ImageView) findViewById(R.id.imageViewPrinterLocation);
        mInputUnitViewGroup = findViewById(R.id.llScanSettingsSource);
        mInputUnitViewGroup.setOnClickListener(this);
        mInputUnitText = (TextView) findViewById(R.id.tvScannerSource);
        mScanSizeViewGroup = findViewById(R.id.llScanSettingsSize);
        mScanSizeViewGroup.setOnClickListener(this);
        mScanSizeText = (TextView) findViewById(R.id.tvScannerSize);
        mScanSizeSeparator = findViewById(R.id.scanSizeSeparator);
        mColorModeViewGroup = findViewById(R.id.llScanSettingsColor);
        mColorModeViewGroup.setOnClickListener(this);
        mColorModeText = (TextView) findViewById(R.id.tvScannerColor);
        mColorModeSeparator = findViewById(R.id.colorModeSeparator);
        mScanResolutionViewGroup = findViewById(R.id.llScanSettingsResolution);
        mScanResolutionViewGroup.setOnClickListener(this);
        mScanResolutionText = (TextView) findViewById(R.id.tvScannerResolution);
        mDuplexViewGroup = findViewById(R.id.llScanSettingsAdvance2Sided);
        mDuplexViewGroup.setOnClickListener(this);
        mDuplexText = (TextView) findViewById(R.id.tvScanner2Sided);
        mBrightnessViewGroup = findViewById(R.id.llScanSettingsDensity);
        mBrightnessViewGroup.setVisibility(View.GONE);
        mBrightnessViewGroup.setOnClickListener(this);
        mBrightnessText = (TextView) findViewById(R.id.tvScannerDensity);
        findViewById(R.id.brightnessSeparator).setVisibility(View.GONE);
        mGammaViewGroup = findViewById(R.id.llScanSettingsGamma);
        mGammaViewGroup.setOnClickListener(this);
        mGammaText = (TextView) findViewById(R.id.tvScannerGamma);
        mInputUnitSeparator = findViewById(R.id.viewScanSettingsSource);
        mDuplexSeparator = findViewById(R.id.viewScanSettingsAdvance2Sided);
        mBrightnessSeparator = findViewById(R.id.brightnessSeparator);
        mProgressBarLayout = findViewById(R.id.progressGetOption);
        setFieldFromIntent(getIntent());
        if (!readEscIVersionChangeIntent(getIntent())) {
            loadData();
        }
        updateScanParamDisplay();
    }

    private void setFieldFromIntent(@Nullable Intent intent) {
        if (intent == null) {
            mHideColorMode = false;
            mHideResolutionMode = false;
            mExternalScanParams = null;
        }
        mHideColorMode = intent.getBooleanExtra("hide-color-mode", false);
        mHideResolutionMode = intent.getBooleanExtra("hide-resolution", false);
        mExternalScanParams = (SharedParamScan) intent.getSerializableExtra("external-scan-params");
    }

    private boolean readEscIVersionChangeIntent(Intent intent) {
        if (intent == null) {
            return false;
        }
        mScannerPropertyWrapper = SettingActivityParams.getScannerPropertyWrapper(intent);
        ScannerPropertyWrapper scannerPropertyWrapper = mScannerPropertyWrapper;
        if (scannerPropertyWrapper == null || scannerPropertyWrapper.getEscIVersion() != 2) {
            return false;
        }
        mScannerChanged = true;
        mI2ScanParamArbiter.notifyScannerChanged(this, mScannerPropertyWrapper.getI2ScannerAllInfo());
        return true;
    }

    private void loadData() {
        mScannerPropertyWrapper = ScannerPropertyWrapper.load(this);
        mI2ScanParamArbiter.makeSelectionList(this, mScannerPropertyWrapper.getI2ScannerAllInfo(), I2ScanParamManager.loadScanI2Params(this));
    }

    private void hideProgress() {
        mProgressBarLayout.setVisibility(View.GONE);
    }

    private void updateScanParamDisplay() {
        updateScannerName();
        displayScannerLocationIcon();
        updateInputUnitDisplay();
        updateScanSize();
        updateImageType();
        updateResolution();
        updateDuplexDisplay();
        updateGammaDisplay();
        updateBrightnessDisplay();
        updateScanSizeSeparator();
    }

    private void updateScanSizeSeparator() {
        mScanSizeSeparator.setVisibility((mColorModeViewGroup.getVisibility() == 0 || mScanResolutionViewGroup.getVisibility() == 0) ? 0 : 8);
    }

    private void displayScannerLocationIcon() {
        String modelName = mScannerPropertyWrapper.getModelName();
        if (modelName == null || modelName.isEmpty()) {
            mPrinterLocationIcon.setVisibility(View.GONE);
            return;
        }
        mPrinterLocationIcon.setVisibility(View.VISIBLE);
        int i = R.drawable.print_local;
        if (mScannerPropertyWrapper.getLocation() == 3) {
            i = R.drawable.print_ip;
        }
        mPrinterLocationIcon.setImageResource(i);
    }

    private void updateScannerName() {
        String ipPrinterUserName;
        if (mScannerPropertyWrapper.getLocation() != 3 || (ipPrinterUserName = new EPPrinterManager(this).getIpPrinterUserName(mScannerPropertyWrapper.getScannerId())) == null) {
            String modelName = mScannerPropertyWrapper.getModelName();
            if (modelName == null || modelName.isEmpty()) {
                mScannerNameText.setText(R.string.str_lbl_title_scan);
            } else {
                mScannerNameText.setText(modelName);
            }
        } else {
            mScannerNameText.setText(ipPrinterUserName);
        }
    }

    private void updateInputUnitDisplay() {
        int i = mI2ScanParamArbiter.getInputUnitCandidates().length <= 1 ? 8 : 0;
        mInputUnitViewGroup.setVisibility(i);
        mInputUnitSeparator.setVisibility(i);
        mInputUnitText.setText(DisplayIdConverter.getInputUnitStringId(mI2ScanParamArbiter.getInputUnit()));
    }

    private void updateScanSize() {
        if (mScanSizeSelected) {
            mScanSizeText.setText(DisplayIdConverter.getScanSizeStringId(mI2ScanParamArbiter.getScanSize()));
            return;
        }
        mScanSizeText.setText(R.string.str_settings_undefine_scansize);
    }

    private void updateImageType() {
        if (mHideColorMode) {
            mColorModeViewGroup.setVisibility(View.GONE);
            mColorModeSeparator.setVisibility(View.GONE);
            return;
        }
        mColorModeViewGroup.setVisibility(View.VISIBLE);
        mColorModeSeparator.setVisibility(View.VISIBLE);
        int colorStringId = DisplayIdConverter.getColorStringId(mI2ScanParamArbiter.getColorMode());
        if (colorStringId == 0) {
            colorStringId = R.string.str_blank;
        }
        mColorModeText.setText(colorStringId);
    }

    private void updateResolution() {
        if (mHideResolutionMode) {
            mScanResolutionViewGroup.setVisibility(View.GONE);
            return;
        }
        mScanResolutionViewGroup.setVisibility(View.VISIBLE);
        mScanResolutionText.setText(DisplayIdConverter.getScanResolutionStrings((Context) this, mI2ScanParamArbiter.getResolution().intValue()));
    }

    private void updateDuplexDisplay() {
        int i = mI2ScanParamArbiter.isDuplexSupported() ? 0 : 8;
        mDuplexSeparator.setVisibility(i);
        mDuplexViewGroup.setVisibility(i);
        mDuplexText.setText(DisplayIdConverter.getYesNoStringId(this, mI2ScanParamArbiter.getDuplex().booleanValue()));
    }

    private void updateBrightnessDisplay() {
        int i = mI2ScanParamArbiter.getColorMode() == EscanI2Lib.ColorMode.MONO_1BIT ? 0 : 8;
        SharedParamScan sharedParamScan = mExternalScanParams;
        if (sharedParamScan != null) {
            i = sharedParamScan.getScan_type() == 3 ? 0 : 8;
        }
        mBrightnessViewGroup.setVisibility(i);
        mBrightnessSeparator.setVisibility(i);
        if (i == 0) {
            mBrightnessText.setText(String.format(Locale.US, "%d", new Object[]{Integer.valueOf(255 - mI2ScanParamArbiter.getDensity())}));
        }
    }

    private void updateGammaDisplay() {
        mGammaText.setText(DisplayIdConverter.getGammaStringId(mI2ScanParamArbiter.getGamma()));
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_done, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() != R.id.menuSettingsDone) {
            return super.onOptionsItemSelected(menuItem);
        }
        saveSettingsAndFinish();
        return true;
    }

    private void saveSettingsAndFinish() {
        try {
            ScanI2Params scanParam = mI2ScanParamArbiter.getScanParam();
            boolean isOldPreviewValid = isOldPreviewValid(mScannerPropertyWrapper, scanParam);
            I2ScanParamManager.saveParams(this, scanParam);
            mScannerPropertyWrapper.saveData(this, mScannerChanged);
            new EPPrinterManager(this).commitIPPrinterInfo();
            Intent intent = new Intent();
            intent.putExtra(RETURN_KEY_OLD_PREVIEW_VALID, isOldPreviewValid);
            setResult(-1, intent);
            finish();
        } catch (IOException unused) {
        }
    }

    private boolean isOldPreviewValid(ScannerPropertyWrapper scannerPropertyWrapper, ScanI2Params scanI2Params) {
        ScannerPropertyWrapper load = ScannerPropertyWrapper.load(this);
        if (scannerPropertyWrapper.getEscIVersion() != scannerPropertyWrapper.getEscIVersion() || !load.getModelName().equals(scannerPropertyWrapper.getModelName())) {
            return false;
        }
        ScanI2Params loadScanI2Params = I2ScanParamManager.loadScanI2Params(this);
        if (loadScanI2Params.inputUnit == scanI2Params.inputUnit && loadScanI2Params.colorMode == scanI2Params.colorMode && loadScanI2Params.resolutionMain == scanI2Params.resolutionMain && loadScanI2Params.resolutionSub == scanI2Params.resolutionSub && loadScanI2Params.duplexTurnDirection == scanI2Params.duplexTurnDirection && loadScanI2Params.duplex == scanI2Params.duplex && loadScanI2Params.manualAdfAlignment == scanI2Params.manualAdfAlignment && loadScanI2Params.density == scanI2Params.density && loadScanI2Params.userGamma == scanI2Params.userGamma) {
            return true;
        }
        return false;
    }

    public void onBackPressed() {
        new EPPrinterManager(this).rollbackIPPrinterInfo();
        super.onBackPressed();
    }

    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.llScannerName) {
            startSelectScannerActivity();
        } else if (id == R.id.llScanSettingsSource) {
            goInputUnitSelection();
        } else if (id == R.id.llScanSettingsSize) {
            goScanSizeSelection();
        } else if (id == R.id.llScanSettingsColor) {
            goImageTypeSelection();
        } else if (id == R.id.llScanSettingsResolution) {
            goScanResolutionSelection();
        } else if (id == R.id.llScanSettingsAdvance2Sided) {
            goDuplicateSelection();
        } else if (id == R.id.llScanSettingsDensity) {
            goBrightnessSelection();
        } else if (id == R.id.llScanSettingsGamma) {
            goGammaSelection();
        }
    }

    private void startSelectScannerActivity() {
        startActivityForResult(ScanSearchActivity.getStartIntent(this, mScannerPropertyWrapper.getScannerId(), mScannerPropertyWrapper.getLocation(), mScannerPropertyWrapper.getSimpleApSsid()), 7);
    }

    private void goImageTypeSelection() {
        startActivityForResult(I2SettingDetailActivity.getStartIntent(this, new ModeListAdapter.Builder(DisplayIdConverter.getColorModeItemIdArray(mI2ScanParamArbiter.getColorModeCandidates()), mI2ScanParamArbiter.getColorModePosition()), R.string.str_settings_color_title), 3);
    }

    private void goInputUnitSelection() {
        startActivityForResult(InputUnitSettingActivity.getStartIntent(this, mI2ScanParamArbiter.getInputUnit() == EscanI2Lib.InputUnit.ADF ? 1 : 0, mI2ScanParamArbiter.isAdfAlignmentMenuValid() ? mI2ScanParamArbiter.getManualAdfAlignmentValue() : -1), 1);
    }

    private void goScanSizeSelection() {
        startActivityForResult(I2SettingDetailActivity.getStartIntent(this, new ModeListAdapter.Builder(DisplayIdConverter.getScanSizeIdArray(mI2ScanParamArbiter.getScanSizeCandidates()), mScanSizeSelected ? mI2ScanParamArbiter.getScanSizePosition() : -1), R.string.str_scanning_size), 2);
    }

    private void goScanResolutionSelection() {
        startActivityForResult(I2SettingDetailActivity.getStartIntent(this, new StringListAdapter.Builder(DisplayIdConverter.getScanResolutionStrings((Context) this, mI2ScanParamArbiter.getResolutionCandidates()), mI2ScanParamArbiter.getResolutionPosition()), R.string.str_settings_resolution_title), 4);
    }

    private void goDuplicateSelection() {
        startActivityForResult(I2DoubleSideScanSettingActivity.getStartIntent(this, mI2ScanParamArbiter.getDuplex().booleanValue(), mI2ScanParamArbiter.getDuplexTurnDirection()), 5);
    }

    private void goBrightnessSelection() {
        startActivityForResult(ScanSettingsAdvanceDensityActivity.getStartIntent(this, mI2ScanParamArbiter.getDensity(), mI2ScanParamArbiter.getDensityChangeable()), 8);
    }

    private void goGammaSelection() {
        startActivityForResult(I2SettingDetailActivity.getStartIntent(this, new ModeListAdapter.Builder(DisplayIdConverter.getGammaStringIdArray(this, mI2ScanParamArbiter.getGammaCandidates()), mI2ScanParamArbiter.getGammaPosition()), R.string.str_settings_gamma_title), 6);
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        if (i != 100) {
            switch (i) {
                case 1:
                    mI2ScanParamArbiter.setInputUnitPosition(InputUnitSettingActivity.getInputUnit(intent));
                    int adfAlignment = InputUnitSettingActivity.getAdfAlignment(intent);
                    if (adfAlignment != -1) {
                        mI2ScanParamArbiter.setManualAdfAlignmentValue(adfAlignment);
                    }
                    updateScanParamDisplay();
                    return;
                case 2:
                    if (i2 == -1 && intent != null) {
                        mScanSizeSelected = true;
                        mI2ScanParamArbiter.setScanSizePosition(I2SettingDetailActivity.getResultPosition(intent));
                        updateScanParamDisplay();
                        return;
                    }
                    return;
                case 3:
                    if (i2 == -1 && intent != null) {
                        mI2ScanParamArbiter.setColorModePosition(I2SettingDetailActivity.getResultPosition(intent));
                        updateScanParamDisplay();
                        return;
                    }
                    return;
                case 4:
                    if (i2 == -1 && intent != null) {
                        mI2ScanParamArbiter.setResolutionPosition(I2SettingDetailActivity.getResultPosition(intent));
                        updateScanParamDisplay();
                        return;
                    }
                    return;
                case 5:
                    if (i2 == -1 && intent != null) {
                        mI2ScanParamArbiter.setDuplexValue(I2DoubleSideScanSettingActivity.getDoubleSideFromReturnIntent(intent));
                        mI2ScanParamArbiter.setDuplexTurnDirection(I2DoubleSideScanSettingActivity.getTurnDirectionFromReturnIntent(intent));
                        updateScanParamDisplay();
                        return;
                    }
                    return;
                case 6:
                    if (i2 == -1 && intent != null) {
                        mI2ScanParamArbiter.setGammaPosition(I2SettingDetailActivity.getResultPosition(intent));
                        updateScanParamDisplay();
                        return;
                    }
                    return;
                case 7:
                    onScannerSelectResult(i2, intent);
                    return;
                case 8:
                    if (i2 == -1 && intent != null) {
                        mI2ScanParamArbiter.setDensity(ScanSettingsAdvanceDensityActivity.getDensityFromReturnIntent(intent), ScanSettingsAdvanceDensityActivity.getChangeAble(intent));
                        updateScanParamDisplay();
                        return;
                    }
                    return;
                default:
                    return;
            }
        } else if (i2 == 1) {
            onScannerSelectResult(-1, intent);
        } else {
            setResult(i2, intent);
            finish();
        }
    }

    private void onScannerSelectResult(int i, Intent intent) {
        if (i != -1) {
            updateIfIpAddressPrinter();
            if (!mScannerPropertyWrapper.isPrinterSet()) {
                transitI1SettingActivity();
                return;
            }
            return;
        }
        mScannerChanged = true;
        mScanSizeSelected = false;
        mScannerPropertyWrapper = SettingActivityParams.getScannerPropertyWrapper(intent);
        ScannerPropertyWrapper scannerPropertyWrapper = mScannerPropertyWrapper;
        if (scannerPropertyWrapper == null) {
            transitI1SettingActivity();
        } else if (scannerPropertyWrapper.getEscIVersion() != 2) {
            transitI1SettingActivity();
        } else {
            mI2ScanParamArbiter.notifyScannerChanged(this, mScannerPropertyWrapper.getI2ScannerAllInfo());
            updateScanParamDisplay();
        }
    }

    private void transitI1SettingActivity() {
        if (SettingActivityParams.returnIfEscIVersionChanged(getIntent())) {
            setResult(1, SettingActivityParams.getSettingReturnIntent(mScannerPropertyWrapper));
            finish();
            return;
        }
        startActivityForResult(SettingActivityParams.getChangeSettingActivityStartIntent(this, mScannerPropertyWrapper, true, mHideColorMode, mHideResolutionMode, mExternalScanParams), 100);
    }

    private void updateIfIpAddressPrinter() {
        if (mScannerPropertyWrapper.getLocation() == 3 && !new EPPrinterManager(this).doseContainScannerIdInIpPrinterList(mScannerPropertyWrapper.getScannerId())) {
            mScannerPropertyWrapper.resetScanner();
            mI2ScanParamArbiter.tmpReset();
            updateScanParamDisplay();
        }
    }

    public static boolean getOldDataValidation(@Nullable Intent intent) {
        return intent == null || intent.getBooleanExtra(RETURN_KEY_OLD_PREVIEW_VALID, false);
    }

    @NonNull
    public static Intent getStartIntent(Context context, boolean z, boolean z2, @Nullable SharedParamScan sharedParamScan) {
        Intent intent = new Intent(context, I2ScanSettingActivity.class);
        intent.putExtra("hide-color-mode", z);
        intent.putExtra("hide-resolution", z2);
        intent.putExtra("external-scan-params", sharedParamScan);
        return intent;
    }
}
