package epson.print;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.media.ExifInterface;
import android.support.p000v4.app.NotificationCompat;
import android.text.InputFilter;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.box.androidsdk.content.requests.BoxRequestsMetadata;
import com.epson.iprint.prtlogger.PrintLog;
import com.fasterxml.jackson.core.JsonPointer;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import epson.common.Utils;
import epson.print.Util.Photo;

public class fileBrower extends ActivityIACommon implements CommonDefine {
    private static final int Menu_Create = 1;
    private static final int Menu_Delete = 1;
    private static final int Menu_Rename = 2;
    private static final int RESULT_RUNTIMEPERMMISSION = 1;
    private String RootPath = CommonDefine.SLASH;
    private String TopPath = CommonDefine.MOUNT_DIR;
    private File currentDirectory = new File(this.TopPath);
    private List<String> directoryEntries = new ArrayList();
    private List<IconifiedText> directotyEntries_new_v2 = new ArrayList();
    private ListView list;
    private AdapterView.AdapterContextMenuInfo listItemIndex;

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.file_browser);
        if (!new File(this.TopPath).isDirectory()) {
            String str = DEFAULT_DIR;
            int lastIndexOf = str.lastIndexOf(CommonDefine.MOUNT_DIR);
            if (lastIndexOf != -1) {
                str = CommonDefine.SLASH + str.substring(lastIndexOf + 5, str.length()) + CommonDefine.SLASH;
            } else if (str.lastIndexOf(CommonDefine.SLASH) != str.length()) {
                str = str + CommonDefine.SLASH;
            }
            TopPath = str;
            currentDirectory = new File(this.TopPath);
        }
        setActionBar(this.TopPath, true);
        list = (ListView) findViewById(R.id.filelist);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
                fileBrower.this.onListItemClick((ListView) adapterView, view, i, j);
            }
        });
        list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long j) {
                if (i == 0) {
                    if (((String) fileBrower.this.directoryEntries.get(i)).equals("..")) {
                        Log.v("select", (String) fileBrower.this.directoryEntries.get(i));
                        return true;
                    }
                    fileBrower filebrower = fileBrower.this;
                    filebrower.registerForContextMenu(filebrower.list);
                }
                if (i <= 2) {
                    return false;
                }
                fileBrower filebrower2 = fileBrower.this;
                filebrower2.registerForContextMenu(filebrower2.list);
                return false;
            }
        });
        list.setBackgroundColor(getResources().getColor(R.color.all_white));
        if (ActivityRequestPermissions.isRuntimePermissionSupported()) {
            String[] strArr = {"android.permission.WRITE_EXTERNAL_STORAGE"};
            ActivityRequestPermissions.Permission permission = new ActivityRequestPermissions.Permission(strArr[0], new String[]{getString(R.string.permission_dialog_title), getString(R.string.permission_dialog_title)}, new String[]{ActivityRequestPermissions.DialogParameter.setMessage2((Context) this, getString(R.string.permission_dialog_message_storage)), ActivityRequestPermissions.DialogParameter.setMessage3A((Context) this, getString(R.string.permission_dialog_message_storage), getString(R.string.permission_function_storage))});
            if (!ActivityRequestPermissions.checkPermission(this, strArr)) {
                ActivityRequestPermissions.requestPermission((Activity) this, permission, 1);
                return;
            }
        }
        startBrowse();
    }

    private void startBrowse() {
        if (Utils.isMediaMounted()) {
            browseToRoot();
            return;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.str_no_sdcard)).setTitle(R.string.unknow_error_title).setCancelable(false).setPositiveButton(getString(R.string.str_exit_btn), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                fileBrower.this.finish();
            }
        });
        builder.create().show();
    }

    protected void onActivityResult(int i, int i2, Intent intent) {
        super.onActivityResult(i, i2, intent);
        if (i == 1) {
            if (i2 != -1) {
                onBackPressed();
            } else {
                startBrowse();
            }
        }
    }

    public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
        super.onCreateContextMenu(contextMenu, view, contextMenuInfo);
        contextMenu.setHeaderTitle(R.string.str_edit_bookmark);
        contextMenu.add(0, 1, 0, R.string.str_delete);
        contextMenu.add(0, 2, 0, R.string.str_rename);
    }

    public boolean onContextItemSelected(MenuItem menuItem) {
        listItemIndex = (AdapterView.AdapterContextMenuInfo) menuItem.getMenuInfo();
        if (this.listItemIndex == null) {
            return true;
        }
        switch (menuItem.getItemId()) {
            case 1:
                final File file = new File(this.currentDirectory.getAbsolutePath() + directoryEntries.get(this.listItemIndex.position));
                final File file2 = currentDirectory;
                C22354 r2 = new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            if (!file.isDirectory() || file.listFiles().length <= 0) {
                                file.delete();
                            } else {
                                fileBrower.this.deleteSubfile(file);
                            }
                            fileBrower.this.browseTo(file2);
                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (IOException e2) {
                            e2.printStackTrace();
                        }
                    }
                };
                C22365 r0 = new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                };
                if (!file.isFile()) {
                    new AlertDialog.Builder(this).setIcon(R.drawable.delete_file).setTitle(getString(R.string.delete_file)).setPositiveButton(getString(R.string.str_no), r0).setNegativeButton(getString(R.string.str_yes), r2).show();
                    break;
                } else {
                    new AlertDialog.Builder(this).setIcon(R.drawable.delete_file).setTitle(getString(R.string.delete_file)).setPositiveButton(getString(R.string.str_no), r0).setNegativeButton(getString(R.string.str_yes), r2).show();
                    break;
                }
            case 2:
                final File file3 = new File(this.currentDirectory.getAbsolutePath() + directoryEntries.get(this.listItemIndex.position));
                final File file4 = currentDirectory;
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                final EditText editText = new EditText(this);
                editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(64)});
                String name = file3.getName();
                final String suffix = Utils.getSuffix(name);
                if (file3.isFile()) {
                    name = Utils.getPreffix(name);
                }
                editText.setText(name);
                builder.setCancelable(false);
                builder.setTitle(R.string.str_rename);
                builder.setIcon(R.drawable.info_image);
                builder.setView(editText);
                builder.setPositiveButton(R.string.str_ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String trim = editText.getText().toString().trim();
                        if (trim == null || trim.length() <= 0) {
                            Toast.makeText(fileBrower.this.getApplicationContext(), R.string.str_error_Filename, 1).show();
                            return;
                        }
                        try {
                            if (file3.isFile() && suffix.length() > 0) {
                                trim = trim + CommonDefine.DOT + suffix;
                            }
                            File file = new File(file3.getParent() + CommonDefine.SLASH + trim);
                            if (!fileBrower.isAvailableFileName(trim)) {
                                Toast.makeText(fileBrower.this.getApplicationContext(), R.string.str_error_Filename, 1).show();
                            } else if (file.exists()) {
                                if (!file3.getPath().equals(file.getPath())) {
                                    Toast.makeText(fileBrower.this.getApplicationContext(), R.string.str_error_Filename, 1).show();
                                }
                            } else if (file3.renameTo(file)) {
                                fileBrower.this.browseTo(file4);
                            } else {
                                Toast.makeText(fileBrower.this.getApplicationContext(), R.string.str_error_Filename, 1).show();
                            }
                        } catch (Exception unused) {
                            Toast.makeText(fileBrower.this.getApplicationContext(), R.string.error, 1).show();
                        }
                    }
                });
                builder.setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.cancel();
                    }
                });
                builder.show();
                break;
        }
        return true;
    }

    public static boolean isAvailableFileName(String str) {
        if (str == null || str.length() == 0) {
            return false;
        }
        char[] cArr = {'<', '>', ':', '*', '?', '\"', JsonPointer.SEPARATOR, '\\', '|', 165};
        for (char indexOf : cArr) {
            if (str.indexOf(indexOf) != -1) {
                return false;
            }
        }
        if (str.startsWith(CommonDefine.DOT)) {
            return false;
        }
        return true;
    }

    public void onBackPressed() {
        try {
            if (!upOneLevel()) {
                finish();
            }
        } catch (NullPointerException unused) {
            super.onBackPressed();
        }
    }

    private void createNewFolder() {
        Log.v("path current", currentDirectory.getAbsolutePath());
        final EditText editText = new EditText(this);
        editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(64)});
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        final String absolutePath = currentDirectory.getAbsolutePath();
        C22398 r3 = new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                String obj = editText.getText().toString();
                if (fileBrower.this.isNameFolder(obj)) {
                    File file = new File(absolutePath + CommonDefine.SLASH + obj);
                    Log.v("create file", absolutePath + CommonDefine.SLASH + obj);
                    if (!file.exists()) {
                        try {
                            if (file.mkdirs()) {
                                fileBrower.this.browseTo(new File(absolutePath));
                            } else {
                                fileBrower.mMessage();
                            }
                        } catch (IllegalArgumentException unused) {
                            fileBrower.mMessage();
                            Log.v("exception", "1");
                        } catch (Exception unused2) {
                            fileBrower.mMessage();
                            Log.v("exception", ExifInterface.GPS_MEASUREMENT_2D);
                        }
                    } else {
                        fileBrower.mMessage();
                    }
                } else {
                    fileBrower.mMessage();
                }
            }
        };
        builder.setTitle("Question").setIcon(R.drawable.new_folder).setView(editText).setTitle(getString(R.string.add_new_folder)).setPositiveButton(R.string.str_ok, r3).setNegativeButton(R.string.str_cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                Log.v("NamVH", "Cant make the new file");
            }
        }).show();
    }

    private void mMessage() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(getString(R.string.str_error_Filename)).setCancelable(false).setPositiveButton(getString(R.string.str_ok), new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        builder.create().show();
    }

    private boolean isNameFolder(String str) {
        return str != null && !str.equals("") && !str.substring(0, 1).equals(CommonDefine.DOT) && str.indexOf(CommonDefine.SLASH) == -1 && str.length() <= 64;
    }

    public boolean onOptionsItemSelected(MenuItem menuItem) {
        if (menuItem.getItemId() == 1) {
            createNewFolder();
        }
        return super.onOptionsItemSelected(menuItem);
    }

    private void browseToRoot() {
        browseTo(new File(this.TopPath));
    }

    private boolean upOneLevel() {
        String parent = currentDirectory.getParent();
        if (parent == null) {
            return true;
        }
        if (!new File(parent).canRead()) {
            return false;
        }
        browseTo(this.currentDirectory.getParentFile());
        return true;
    }

    private boolean isFileText(String str) {
        return str != null && Utils.checkMimeType(str, CommonDefine.TEXT_TYPE);
    }

    private boolean isFilePdf(String str) {
        return str != null && Utils.checkMimeType(str, "application/pdf");
    }

    private boolean getFileType(String str) {
        if (str == null) {
            return false;
        }
        return Utils.isGConvertFile(str) || isFilePdf(str) || Photo.IsFilePhoto(str) || isFileText(str);
    }

    private boolean getFileSize(String str) {
        File file = new File(str);
        if (!file.exists() || file.isDirectory()) {
            return false;
        }
        return (!Photo.IsFilePhoto(str) || file.length() < 3145728) ? true : true;
    }

    private boolean getFileShow(String str) {
        File file = new File(str);
        if (!file.exists()) {
            return false;
        }
        if (!file.isDirectory() && !getFileType(str)) {
            return false;
        }
        return true;
    }

    private void browseTo(File file) {
        if (file.isDirectory()) {
            currentDirectory = file;
            fill(file.listFiles());
            return;
        }
        try {
            if (Photo.IsFilePhoto(file.getAbsolutePath())) {
                startPhotoPreview(file);
                return;
            }
            if (!isFilePdf(file.getAbsolutePath())) {
                if (!Utils.isGConvertFile(file.getAbsolutePath())) {
                    if (isFileText(file.getAbsolutePath())) {
                        Intent intent = new Intent(this, WebviewActivity.class);
                        intent.putExtra("from", 3);
                        intent.putExtra("android.intent.extra.TEXT", "file:/" + file.getAbsolutePath());
                        startActivity(intent);
                        return;
                    }
                    Toast.makeText(getBaseContext(), getString(R.string.file_size_notsupport), 0).show();
                    return;
                }
            }
            if (getFileSize(file.getAbsolutePath())) {
                Intent intent2 = new Intent(this, ActivityDocsPrintPreview.class);
                intent2.putExtra("from", 3);
                intent2.putExtra(CommonDefine.SEND_DOCUMENT_VIEW, file.getAbsolutePath());
                intent2.putExtra("print_log", getPrintLog(file));
                startActivity(intent2);
                return;
            }
            Log.v("file size", ">max");
            Toast.makeText(getBaseContext(), getString(R.string.file_size_notsupport), 0).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startPhotoPreview(File file) {
        Intent intent = new Intent(this, ActivityViewImageSelect.class);
        intent.putExtra("from", 3);
        intent.putExtra(ActivityViewImageSelect.PARAMS_KEY_FROM_EPSON, true);
        intent.setAction("android.intent.action.SEND");
        intent.putExtra("android.intent.extra.STREAM", Uri.parse(file.getAbsolutePath()));
        if (Utils.checkMimeType(file.getAbsolutePath(), "image/png")) {
            intent.setType("image/png");
        }
        intent.putExtra(CommonDefine.STYPE, true);
        intent.putExtra("print_log", getPrintLog(file));
        startActivity(intent);
    }

    private PrintLog getPrintLog(File file) {
        PrintLog printLog = new PrintLog();
        printLog.uiRoute = 2;
        printLog.originalFileExtension = PrintLog.getFileExtension(file);
        return printLog;
    }

    private void fill(File[] fileArr) {
        Log.v(NotificationCompat.CATEGORY_CALL, "fill function");
        directoryEntries.clear();
        directotyEntries_new_v2.clear();
        if (fileArr != null) {
            Log.v("abc", String.valueOf(fileArr.length));
            int length = currentDirectory.getAbsolutePath().length();
            for (File file : fileArr) {
                if (!file.getName().substring(0, 1).equals(CommonDefine.DOT)) {
                    if (isFilePdf(file.getAbsolutePath())) {
                        getFileShow(file.getAbsolutePath());
                    }
                    if (!file.getAbsolutePath().equals("/mnt/secure") && !file.getAbsolutePath().equals("/mnt/asec") && !file.getAbsolutePath().equals("/mnt/.lfs") && !file.getAbsolutePath().equals("/mnt/obb") && ((!this.currentDirectory.getAbsolutePath().equals(CommonDefine.MNT) || !file.isDirectory() || file.listFiles() != null) && getFileShow(file.getAbsolutePath()))) {
                        directoryEntries.add(file.getAbsolutePath().substring(length));
                        directotyEntries_new_v2.add(createIcon(file.getAbsolutePath()));
                    }
                }
            }
            Collections.sort(this.directoryEntries, new StringComparator());
            Collections.sort(this.directotyEntries_new_v2, new IconifiedText());
        }
        setTitle(this.currentDirectory.getAbsolutePath());
        Log.v("getparent", currentDirectory.getParent());
        if (!this.currentDirectory.getParent().equals(this.RootPath)) {
            Log.v("compare", "not equals");
            Log.v("getparent currentDirectory", currentDirectory.getParent());
            directoryEntries.add(0, "..");
            directotyEntries_new_v2.add(0, new IconifiedText("..", getResources().getDrawable(R.drawable.parent_folder), true));
        }
        IconifiedTextListAdapter iconifiedTextListAdapter = new IconifiedTextListAdapter(this);
        iconifiedTextListAdapter.setListItems(this.directotyEntries_new_v2);
        list.setAdapter(iconifiedTextListAdapter);
    }

    class StringComparator implements Comparator<String> {
        public StringComparator() {
        }

        public int compare(String str, String str2) {
            if (str == null || str2 == null) {
                return 0;
            }
            if (str.equalsIgnoreCase(CommonDefine.DOT)) {
                return -1;
            }
            if (str2.equalsIgnoreCase(CommonDefine.DOT)) {
                return 1;
            }
            return str.compareToIgnoreCase(str2);
        }
    }

    protected void onListItemClick(ListView listView, View view, int i, long j) {
        Log.v("onclick", String.valueOf(i));
        String str = directoryEntries.get(i);
        Log.v(BoxRequestsMetadata.UpdateItemMetadata.BoxMetadataUpdateTask.PATH, str);
        if (str.equals(CommonDefine.DOT)) {
            browseTo(new File(this.TopPath));
        } else if (str.equals("..")) {
            upOneLevel();
        } else if (!str.startsWith(CommonDefine.DOT)) {
            browseTo(new File(this.currentDirectory.getAbsolutePath() + CommonDefine.SLASH + directotyEntries_new_v2.get(i).getText()));
        }
    }

    private IconifiedText createIcon(String str) {
        File file = new File(str);
        if (file.isDirectory()) {
            return new IconifiedText(file.getName(), getResources().getDrawable(R.drawable.folder), true);
        }
        if (Photo.IsFilePhoto(str)) {
            return new IconifiedText(file.getName(), getResources().getDrawable(R.drawable.image), false);
        }
        if (Utils.isGConvertFile(str) || isFilePdf(str) || isFileText(str)) {
            return new IconifiedText(file.getName(), getResources().getDrawable(R.drawable.file), false);
        }
        return new IconifiedText(file.getName(), getResources().getDrawable(R.drawable.icon), false);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, 1, 0, getString(R.string.new_folder)).setIcon(R.drawable.new_folder).setShortcut('0', 'f');
        return true;
    }

    private void deleteSubfile(File file) throws SecurityException, IOException {
        for (File file2 : file.listFiles()) {
            if (!fileEnableDelete(file2)) {
                deleteSubfile(file2);
            }
            file2.delete();
        }
        file.delete();
        if (file.exists()) {
            throw new IOException("Unable to delete directory hierarchy \"" + file.getAbsolutePath() + "\"");
        }
    }

    private boolean fileEnableDelete(File file) {
        if (file.isFile()) {
            return true;
        }
        if (!file.isDirectory() || file.list().length != 0) {
            return false;
        }
        return true;
    }
}
