package info.knacki.pass.ui.passwordList;

import android.app.Activity;
import android.view.MenuItem;
import android.widget.PopupMenu;

import java.io.File;

import info.knacki.pass.R;
import info.knacki.pass.io.PathUtils;

public class EditablePasswordListView<T extends Activity & PasswordEditListener> extends PasswordListView<T> implements PopupMenu.OnMenuItemClickListener  {
    private PasswordView fSelectedPassword;
    private boolean fDisplayHiddenFiles;

    public EditablePasswordListView(T ctx, String rootPath, boolean displayHidden) {
        super(ctx, rootPath);
        fDisplayHiddenFiles = displayHidden;
    }

    public void SetDisplayHiddenFiles(boolean displayHidden) {
        fDisplayHiddenFiles = displayHidden;
        refresh();
    }

    @Override
    protected boolean IsHidden(File f) {
        return (PathUtils.IsHidden(f.getAbsolutePath()) != fDisplayHiddenFiles);
    }

    protected int GetMenuForFile(FileIdentity f) {
        if (f.fIsDir)
            return R.menu.context_dir_menu;
        return (PathUtils.IsHidden(f.fName)) ? R.menu.context_trashed_menu : R.menu.context_file_menu;
    }

    protected void AddContextMenu(final FileIdentity file, final PasswordView pv) {
        if (file.isParent())
            return;
        pv.setOnLongClickListener(v -> {
            fSelectedPassword = pv;
            PopupMenu menu = new PopupMenu(fClickListener, pv);
            menu.getMenuInflater().inflate(GetMenuForFile(file), menu.getMenu());
            menu.setOnMenuItemClickListener(EditablePasswordListView.this);
            menu.show();
            return true;
        });
    }

    @Override
    protected PasswordView CreateView(FileIdentity file) {
        final PasswordView pv = super.CreateView(file);
        AddContextMenu(file, pv);
        return pv;
    }

    @Override
    public boolean onMenuItemClick(MenuItem item) {
        boolean found = true;

        switch (item.getItemId()) {
            case R.id.remove:
                if (fSelectedPassword.IsDir()) {
                    fClickListener.OnRemoveDirectory(new File(fCurrentDir + "/" + fSelectedPassword.fFullName));
                } else {
                    fClickListener.OnRemovePassword(new File(fCurrentDir + "/" + fSelectedPassword.fFullName));
                }
                break;

            case R.id.restore:
                fClickListener.OnRestorePassword(new File(fCurrentDir + "/" + fSelectedPassword.fFullName));
                break;

            case R.id.encryption_information:
                fClickListener.OnEncryptionInformation(new File(fCurrentDir +"/" +fSelectedPassword.fFullName));
                break;

            case R.id.clipboard:
                fClickListener.OnCopyToClipboard(new File(fCurrentDir +"/" +fSelectedPassword.fFullName));
                break;

            default:
                found = false;
                break;
        }
        fSelectedPassword = null;
        return found;
    }
}
