package epson.server.screens;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.media.ExifInterface;
import android.support.p000v4.media.session.PlaybackStateCompat;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import epson.common.Constants;
import epson.common.ExternalFileUtils;
import epson.print.ActivityIACommon;
import epson.print.R;
import epson.print.CommonDefine;
import epson.print.ScanFileNumber;
import epson.print.Util.EPLog;
import epson.print.Util.Utils;
import epson.print.fileBrower;
import epson.provider.ScannedFileProvider;
import epson.scan.lib.libHaru;
import epson.server.utils.Define;
import epson.server.utils.MyUtility;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;

public class UploadScreen extends ActivityIACommon implements CommonDefine {
    private static final int LOCAL_SAVED = 16;
    private static final int SET_SCREENSTATE = 0;
    private static final String TAG = "UploadScreen";
    private final int MAX_COPY_COUNT = 99;
    private RadioGroup chooseFileType;
    private int count;
    String currentFileName;
    Dialog errorDialog;
    boolean isSaved = false;
    private Button mClear;
    private EditText mFileName;
    private String mFileType = Constants.PDF_TYPE;
    private Handler mHandler = new Handler(new Handler.Callback() {
        public boolean handleMessage(Message message) {
            int i = message.what;
            if (i == 0) {
                UploadScreen.this.setScreenState(false);
            } else if (i == 16) {
                EPLog.i("createUploadThread", "5:" + UploadScreen.this.isSaved);
                if (UploadScreen.this.isSaved) {
                    UploadScreen.this.setResult(-1, UploadScreen.this.getIntent());
                    UploadScreen.this.finish();
                } else {
                    EPLog.i("createUploadThread", "6:" + UploadScreen.this.isSaved);
                    UploadScreen uploadScreen = UploadScreen.this;
                    uploadScreen.errorDialog = new ErrorDialog(uploadScreen, R.style.AppTheme_Translucent, 4, 0, false);
                    UploadScreen.this.errorDialog.show();
                    UploadScreen.this.setScreenState(false);
                }
            }
            return false;
        }
    });
    private boolean mIsRename;
    private ArrayList<String> mListFilePath;
    private Button mSaveBtn;
    private Vector<File> mSaveFiles = new Vector<>();
    private Utils utils = new Utils();

    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.upload_dialog);
        setActionBar("", true);
        mSaveBtn = (Button) findViewById(R.id.save_button);
        mFileName = (EditText) findViewById(R.id.upload_dialog_file_name);
        mFileName.setFilters(new InputFilter[]{new InputFilter.LengthFilter(64)});
        mFileName.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            public void onFocusChange(View view, boolean z) {
                if (!z) {
                    UploadScreen.mFileName.extendSelection(0);
                    UploadScreen.mFileName.setSelection(0);
                }
            }
        });
        mClear = (Button) findViewById(R.id.clear_name_btn);
        count = ScanFileNumber.getCount(this);
        EditText editText = mFileName;
        editText.setText("EPSON" + utils.editNumber(this.count));
        if (mFileName.getText().toString().length() > 0) {
            mClear.setVisibility(View.VISIBLE);
        }
        mFileName.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) {
            }

            public void afterTextChanged(Editable editable) {
                if (UploadScreen.mFileName.getText().toString().length() > 0) {
                    UploadScreen.mClear.setVisibility(View.VISIBLE);
                    UploadScreen.mSaveBtn.setEnabled(true);
                    return;
                }
                UploadScreen.mClear.setVisibility(View.GONE);
                UploadScreen.mSaveBtn.setEnabled(false);
            }
        });
        mClear.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                UploadScreen.mFileName.getText().clear();
            }
        });
        chooseFileType = (RadioGroup) findViewById(R.id.file_type_for_upload);
        chooseFileType.check(R.id.pdf_type);
        mFileType = Constants.PDF_TYPE;
        chooseFileType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (i == R.id.jpeg_type) {
                    String unused = UploadScreen.mFileType = Constants.JPEG_TYPE;
                    EPLog.i("checkedId", "....." + UploadScreen.mFileType);
                } else if (i == R.id.pdf_type) {
                    String unused2 = UploadScreen.mFileType = Constants.PDF_TYPE;
                    EPLog.i("checkedId", "....." + UploadScreen.mFileType);
                }
            }
        });
        mListFilePath = getIntent().getStringArrayListExtra(Define.SAVING_FILE_PATH);
        Long l = 0L;
        Iterator<String> it = mListFilePath.iterator();
        while (it.hasNext()) {
            l = Long.valueOf(l.longValue() + new File(it.next()).length());
        }
        float longValue = (float) (l.longValue() / PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID);
        if (longValue > 500.0f) {
            ((TextView) findViewById(R.id.file_size)).setText("" + MyUtility.mathRound((longValue / 1024.0f), 2) + "MB");
        } else {
            ((TextView) findViewById(R.id.file_size)).setText("" + MyUtility.mathRound(longValue, 2) + "KB");
        }
        switch (getIntent().getIntExtra("for", 7)) {
            case 6:
                setTitle(getString(R.string.open_in));
                mSaveBtn.setText(getString(R.string.open_in));
                mSaveBtn.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        String str;
                        boolean z;
                        Intent intent = new Intent();
                        try {
                            if (!fileBrower.isAvailableFileName(UploadScreen.mFileName.getText().toString())) {
                                Toast.makeText(UploadScreen.this.getApplicationContext(), R.string.str_error_Filename, 1).show();
                                return;
                            }
                            intent.setAction("android.intent.action.SEND");
                            if (UploadScreen.mFileType.equals(Constants.PDF_TYPE)) {
                                ArrayList arrayList = new ArrayList();
                                Iterator it = UploadScreen.mListFilePath.iterator();
                                while (it.hasNext()) {
                                    arrayList.add((String) it.next());
                                }
                                libHaru libharu = new libHaru();
                                String scannedImageDir = ExternalFileUtils.getInstance(UploadScreen.this).getScannedImageDir();
                                File file = new File(scannedImageDir, UploadScreen.mFileName.getText().toString() + CommonDefine.FileType_PDF);
                                libharu.createPDF(arrayList, file.getAbsolutePath());
                                intent.putExtra("android.intent.extra.STREAM", ScannedFileProvider.getUriForFile(UploadScreen.this, file));
                                intent.setType("application/pdf");
                            } else {
                                String obj = UploadScreen.mFileName.getText().toString();
                                if (!obj.equals("EPSON" + UploadScreen.this.utils.editNumber(UploadScreen.this.count))) {
                                    str = UploadScreen.mFileName.getText().toString();
                                    z = true;
                                } else if (UploadScreen.mListFilePath.size() == 1) {
                                    str = UploadScreen.mFileName.getText().toString();
                                    z = false;
                                } else {
                                    str = "EPSON";
                                    z = false;
                                }
                                ArrayList arrayList2 = new ArrayList();
                                int access$500 = UploadScreen.this.count;
                                ExternalFileUtils.getInstance(UploadScreen.this).createTempFolder(ExternalFileUtils.getInstance(UploadScreen.this).getScannedImageDir());
                                if (UploadScreen.mListFilePath.size() == 1) {
                                    UploadScreen uploadScreen = UploadScreen.this;
                                    arrayList2.add(ScannedFileProvider.getUriForFile(UploadScreen.this, MyUtility.createTempFile(uploadScreen, (String) UploadScreen.mListFilePath.get(0), str + ".jpg")));
                                } else {
                                    if (z) {
                                        access$500 = 1;
                                    }
                                    for (int i = 0; i < UploadScreen.mListFilePath.size(); i++) {
                                        UploadScreen uploadScreen2 = UploadScreen.this;
                                        access$500++;
                                        arrayList2.add(ScannedFileProvider.getUriForFile(UploadScreen.this, MyUtility.createTempFile(uploadScreen2, (String) UploadScreen.mListFilePath.get(i), str + UploadScreen.this.utils.editNumber(access$500) + ".jpg")));
                                    }
                                }
                                if (arrayList2.size() <= 1) {
                                    intent.putExtra("android.intent.extra.STREAM", (Parcelable) arrayList2.get(0));
                                } else {
                                    intent.setAction("android.intent.action.SEND_MULTIPLE");
                                    intent.putParcelableArrayListExtra("android.intent.extra.STREAM", arrayList2);
                                }
                                intent.setType("image/jpg");
                            }
                            UploadScreen.this.startActivity(Intent.createChooser(intent, UploadScreen.this.getString(R.string.open_in)));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
                return;
            case 7:
                setTitle(getString(R.string.local_memory));
                ((TextView) findViewById(R.id.upload_dialog_save_path)).setText(EPSONIPRINT_FOLDER);
                findViewById(R.id.upload_dialog_save_path).setVisibility(View.VISIBLE);
                mSaveBtn.setText(getString(R.string.str_save));
                mSaveBtn.setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view) {
                        String str;
                        if (!fileBrower.isAvailableFileName(UploadScreen.mFileName.getText().toString())) {
                            Toast.makeText(UploadScreen.this.getApplicationContext(), R.string.str_error_Filename, 1).show();
                        } else if (UploadScreen.mFileName.getText().toString().length() > 0) {
                            UploadScreen.this.setScreenState(true);
                            Iterator it = UploadScreen.mListFilePath.iterator();
                            while (it.hasNext()) {
                                UploadScreen.mSaveFiles.add(new File((String) it.next()));
                            }
                            String obj = UploadScreen.mFileName.getText().toString();
                            if (!obj.equals("EPSON" + UploadScreen.this.utils.editNumber(UploadScreen.this.count))) {
                                boolean unused = UploadScreen.mIsRename = true;
                                str = UploadScreen.mFileName.getText().toString();
                            } else if (UploadScreen.mSaveFiles.size() == 1) {
                                boolean unused2 = UploadScreen.mIsRename = false;
                                str = UploadScreen.mFileName.getText().toString();
                            } else {
                                boolean unused3 = UploadScreen.mIsRename = false;
                                str = "EPSON";
                            }
                            UploadScreen uploadScreen = UploadScreen.this;
                            uploadScreen.currentFileName = str;
                            uploadScreen.createUploadThread();
                        }
                    }
                });
                return;
            default:
                return;
        }
    }

    private void createUploadThread() {
        new Thread() {
            public void run() {
                File file;
                UploadScreen.this.isSaved = false;
                try {
                    MyUtility.createFolder(CommonDefine.EPSONIPRINT_FOLDER);
                    int access$500 = UploadScreen.this.count;
                    if (UploadScreen.mSaveFiles.size() != 1) {
                        if (UploadScreen.mIsRename) {
                            access$500 = 1;
                        }
                        if (!UploadScreen.mFileType.equals(Constants.PDF_TYPE)) {
                            Iterator it = UploadScreen.mSaveFiles.iterator();
                            while (true) {
                                if (!it.hasNext()) {
                                    break;
                                }
                                UploadScreen.this.isSaved = true;
                                UploadScreen uploadScreen = UploadScreen.this;
                                String absolutePath = ((File) it.next()).getAbsolutePath();
                                File createTempFile = MyUtility.createTempFile(uploadScreen, absolutePath, UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + ".jpg");
                                if (createTempFile == null) {
                                    UploadScreen.this.isSaved = false;
                                    break;
                                }
                                File file2 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + ".jpg");
                                if (file2.exists() && !UploadScreen.mIsRename) {
                                    int i = 1;
                                    while (true) {
                                        File file3 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + " (" + i + ")" + ".jpg");
                                        if (!file3.exists()) {
                                            file2 = file3;
                                            break;
                                        } else if (i >= 99) {
                                            file2 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + " (" + 99 + ")" + ".jpg");
                                            break;
                                        } else {
                                            i++;
                                        }
                                    }
                                }
                                access$500++;
                                MyUtility.copy(createTempFile, file2);
                                UploadScreen.this.addMediaStorage(file2.getAbsolutePath());
                                if (createTempFile.isFile()) {
                                    createTempFile.delete();
                                }
                            }
                        } else {
                            ArrayList arrayList = new ArrayList();
                            Iterator it2 = UploadScreen.mSaveFiles.iterator();
                            while (it2.hasNext()) {
                                arrayList.add(((File) it2.next()).getAbsolutePath());
                            }
                            libHaru libharu = new libHaru();
                            if (UploadScreen.mIsRename) {
                                file = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + CommonDefine.FileType_PDF);
                            } else {
                                file = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + CommonDefine.FileType_PDF);
                            }
                            if (file.exists() && !UploadScreen.mIsRename) {
                                int i2 = 1;
                                while (true) {
                                    File file4 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + " (" + i2 + ")" + CommonDefine.FileType_PDF);
                                    if (!file4.exists()) {
                                        file = file4;
                                        break;
                                    } else if (i2 >= 99) {
                                        file = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + UploadScreen.this.utils.editNumber(access$500) + " (" + 99 + ")" + CommonDefine.FileType_PDF);
                                        break;
                                    } else {
                                        i2++;
                                    }
                                }
                            }
                            if (libharu.createPDF(arrayList, file.getAbsolutePath()) == 0) {
                                UploadScreen.this.isSaved = true;
                                UploadScreen.this.addMediaStorage(file.getAbsolutePath());
                            }
                        }
                    } else if (UploadScreen.mFileType.equals(Constants.PDF_TYPE)) {
                        ArrayList arrayList2 = new ArrayList();
                        Iterator it3 = UploadScreen.mSaveFiles.iterator();
                        while (it3.hasNext()) {
                            arrayList2.add(((File) it3.next()).getAbsolutePath());
                        }
                        libHaru libharu2 = new libHaru();
                        File file5 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + CommonDefine.FileType_PDF);
                        if (file5.exists() && !UploadScreen.mIsRename) {
                            int i3 = 1;
                            while (true) {
                                File file6 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + " (" + i3 + ")" + CommonDefine.FileType_PDF);
                                if (!file6.exists()) {
                                    file5 = file6;
                                    break;
                                } else if (i3 >= 99) {
                                    file5 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + " (" + 99 + ")" + CommonDefine.FileType_PDF);
                                    break;
                                } else {
                                    i3++;
                                }
                            }
                        }
                        if (libharu2.createPDF(arrayList2, file5.getAbsolutePath()) == 0) {
                            UploadScreen.this.isSaved = true;
                            UploadScreen.this.addMediaStorage(file5.getAbsolutePath());
                        }
                    } else {
                        EPLog.i("createUploadThread", "1");
                        UploadScreen uploadScreen2 = UploadScreen.this;
                        String absolutePath2 = ((File) UploadScreen.mSaveFiles.get(0)).getAbsolutePath();
                        File createTempFile2 = MyUtility.createTempFile(uploadScreen2, absolutePath2, UploadScreen.this.currentFileName + ".jpg");
                        EPLog.i("createUploadThread", ExifInterface.GPS_MEASUREMENT_2D + createTempFile2);
                        if (createTempFile2 != null) {
                            File file7 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + ".jpg");
                            StringBuilder sb = new StringBuilder();
                            sb.append(ExifInterface.GPS_MEASUREMENT_3D);
                            sb.append(file7);
                            EPLog.i("createUploadThread", sb.toString());
                            if (file7.exists() && !UploadScreen.mIsRename) {
                                int i4 = 1;
                                while (true) {
                                    File file8 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + " (" + i4 + ")" + ".jpg");
                                    if (!file8.exists()) {
                                        file7 = file8;
                                        break;
                                    } else if (i4 >= 99) {
                                        file7 = new File(CommonDefine.EPSONIPRINT_FOLDER + UploadScreen.this.currentFileName + " (" + 99 + ")" + ".jpg");
                                        break;
                                    } else {
                                        i4++;
                                    }
                                }
                            }
                            MyUtility.copy(createTempFile2, file7);
                            UploadScreen.this.addMediaStorage(file7.getAbsolutePath());
                            if (createTempFile2.isFile()) {
                                createTempFile2.delete();
                            }
                            UploadScreen.this.isSaved = true;
                            EPLog.i("createUploadThread", "4:" + UploadScreen.this.isSaved);
                        }
                    }
                    UploadScreen.mSaveFiles.clear();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                UploadScreen.mHandler.sendEmptyMessageDelayed(16, 1500);
            }
        }.start();
    }

    private void addMediaStorage(String str) {
        EPLog.i(TAG, "MediaScannerConnection.scanFile path=" + str);
        MediaScannerConnection.scanFile(this, new String[]{str}, (String[]) null, (MediaScannerConnection.OnScanCompletedListener) null);
    }

    private class ErrorDialog extends Dialog {
        private int mErrorCode;
        private int mExtraCode;
        private boolean mIsCloseDialog;

        public ErrorDialog(Context context, int i, int i2, int i3, boolean z) {
            super(context, i);
            mErrorCode = i2;
            mIsCloseDialog = z;
            mExtraCode = i3;
        }

        protected void onCreate(Bundle bundle) {
            requestWindowFeature(1);
            super.onCreate(bundle);
            View inflate = getLayoutInflater().inflate(R.layout.my_dialog_layout, (ViewGroup) null);
            int i = mErrorCode;
            if (i != 16) {
                switch (i) {
                    case 0:
                        ((TextView) inflate.findViewById(R.id.dialog_title)).setText(UploadScreen.this.getString(R.string.authenticate_error_title));
                        ((TextView) inflate.findViewById(R.id.dialog_content)).setText(UploadScreen.this.getString(R.string.authenticate_error_mes));
                        break;
                    case 1:
                        ((TextView) inflate.findViewById(R.id.dialog_title)).setText(UploadScreen.this.getString(R.string.download_error_title));
                        ((TextView) inflate.findViewById(R.id.dialog_content)).setText(UploadScreen.this.getString(R.string.download_error_mes));
                        break;
                    case 2:
                        ((TextView) inflate.findViewById(R.id.dialog_title)).setText(UploadScreen.this.getString(R.string.upload_error_title));
                        ((TextView) inflate.findViewById(R.id.dialog_content)).setText(UploadScreen.this.getString(R.string.upload_error_mes));
                        break;
                    case 3:
                        ((TextView) inflate.findViewById(R.id.dialog_title)).setText(UploadScreen.this.getString(R.string.error));
                        ((TextView) inflate.findViewById(R.id.dialog_content)).setText(UploadScreen.this.getString(R.string.network_error_mes));
                        break;
                    case 4:
                        ((TextView) inflate.findViewById(R.id.dialog_title)).setText(UploadScreen.this.getString(R.string.upload_error_title));
                        ((TextView) inflate.findViewById(R.id.dialog_content)).setText(UploadScreen.this.getString(R.string.str_error_Filename));
                        break;
                }
            } else {
                ((TextView) inflate.findViewById(R.id.dialog_title)).setText(UploadScreen.this.getString(R.string.unknow_error_title));
                ((TextView) inflate.findViewById(R.id.dialog_content)).setText(UploadScreen.this.getString(R.string.unknow_error_mes));
            }
            ((Button) inflate.findViewById(R.id.f337ok)).setOnClickListener(new View.OnClickListener() {
                public void onClick(View view) {
                    ErrorDialog.this.dismiss();
                    int unused = UploadScreen.this.count = 0;
                    if (ErrorDialog.mIsCloseDialog) {
                        int unused2 = ErrorDialog.mExtraCode;
                        int unused3 = ErrorDialog.mExtraCode;
                    }
                }
            });
            setContentView(inflate);
        }

        public boolean onKeyDown(int i, KeyEvent keyEvent) {
            return keyEvent.getAction() == 0 && i == 84;
        }
    }

    private void setScreenState(Boolean bool) {
        if (!bool.booleanValue()) {
            findViewById(R.id.in_progress).setVisibility(View.GONE);
            mSaveBtn.setEnabled(true);
            chooseFileType.setEnabled(true);
            return;
        }
        mSaveBtn.setEnabled(false);
        chooseFileType.setEnabled(false);
        findViewById(R.id.in_progress).setVisibility(View.VISIBLE);
    }

    private void copyFile(File file, File file2) throws Exception {
        FileChannel channel = new FileInputStream(file).getChannel();
        FileChannel channel2 = new FileOutputStream(file2).getChannel();
        channel.transferTo(0, channel.size(), channel2);
        channel.close();
        channel2.close();
    }
}
