package com.github.mjdev.libaums.fs.fat32;

import android.util.Log;
import com.github.mjdev.libaums.driver.BlockDeviceDriver;
import com.github.mjdev.libaums.fs.UsbFile;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/* JADX INFO: loaded from: classes.dex */
public class FatDirectory implements UsbFile {
    private static String TAG = "FatDirectory";
    private BlockDeviceDriver blockDevice;
    private Fat32BootSector bootSector;
    private ClusterChain chain;
    private List<FatLfnDirectoryEntry> entries;
    private FatLfnDirectoryEntry entry;
    private FAT fat;
    private boolean hasBeenInited;
    private FatDirectory parent;
    private String volumeLabel;
    private Map<String, FatLfnDirectoryEntry> lfnMap = new HashMap();
    private Map<ShortName, FatDirectoryEntry> shortNameMap = new HashMap();

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public boolean isDirectory() {
        return true;
    }

    private FatDirectory(BlockDeviceDriver blockDeviceDriver, FAT fat, Fat32BootSector fat32BootSector, FatDirectory fatDirectory) {
        this.blockDevice = blockDeviceDriver;
        this.fat = fat;
        this.bootSector = fat32BootSector;
        this.parent = fatDirectory;
    }

    static FatDirectory create(FatLfnDirectoryEntry fatLfnDirectoryEntry, BlockDeviceDriver blockDeviceDriver, FAT fat, Fat32BootSector fat32BootSector, FatDirectory fatDirectory) {
        FatDirectory fatDirectory2 = new FatDirectory(blockDeviceDriver, fat, fat32BootSector, fatDirectory);
        fatDirectory2.entry = fatLfnDirectoryEntry;
        return fatDirectory2;
    }

    static FatDirectory readRoot(BlockDeviceDriver blockDeviceDriver, FAT fat, Fat32BootSector fat32BootSector) throws IOException {
        FatDirectory fatDirectory = new FatDirectory(blockDeviceDriver, fat, fat32BootSector, null);
        fatDirectory.chain = new ClusterChain(fat32BootSector.getRootDirStartCluster(), blockDeviceDriver, fat, fat32BootSector);
        fatDirectory.init();
        return fatDirectory;
    }

    private void init() throws IOException {
        if (this.chain == null) {
            this.chain = new ClusterChain(this.entry.getStartCluster(), this.blockDevice, this.fat, this.bootSector);
        }
        if (this.entries == null) {
            this.entries = new ArrayList();
        }
        if (this.entries.size() == 0 && !this.hasBeenInited) {
            readEntries();
        }
        this.hasBeenInited = true;
    }

    private void readEntries() throws IOException {
        FatDirectoryEntry fatDirectoryEntry;
        ByteBuffer byteBufferAllocate = ByteBuffer.allocate((int) this.chain.getLength());
        this.chain.read(0L, byteBufferAllocate);
        ArrayList arrayList = new ArrayList();
        byteBufferAllocate.flip();
        while (byteBufferAllocate.remaining() > 0 && (fatDirectoryEntry = FatDirectoryEntry.read(byteBufferAllocate)) != null) {
            if (fatDirectoryEntry.isLfnEntry()) {
                arrayList.add(fatDirectoryEntry);
            } else if (fatDirectoryEntry.isVolumeLabel()) {
                if (!isRoot()) {
                    Log.w(TAG, "volume label in non root dir!");
                }
                this.volumeLabel = fatDirectoryEntry.getVolumeLabel();
                Log.d(TAG, "volume label: " + this.volumeLabel);
            } else if (fatDirectoryEntry.isDeleted()) {
                arrayList.clear();
            } else {
                addEntry(FatLfnDirectoryEntry.read(fatDirectoryEntry, arrayList), fatDirectoryEntry);
                arrayList.clear();
            }
        }
    }

    private void addEntry(FatLfnDirectoryEntry fatLfnDirectoryEntry, FatDirectoryEntry fatDirectoryEntry) {
        this.entries.add(fatLfnDirectoryEntry);
        this.lfnMap.put(fatLfnDirectoryEntry.getName().toLowerCase(Locale.getDefault()), fatLfnDirectoryEntry);
        this.shortNameMap.put(fatDirectoryEntry.getShortName(), fatDirectoryEntry);
    }

    void removeEntry(FatLfnDirectoryEntry fatLfnDirectoryEntry) {
        this.entries.remove(fatLfnDirectoryEntry);
        this.lfnMap.remove(fatLfnDirectoryEntry.getName().toLowerCase(Locale.getDefault()));
        this.shortNameMap.remove(fatLfnDirectoryEntry.getActualEntry().getShortName());
    }

    void renameEntry(FatLfnDirectoryEntry fatLfnDirectoryEntry, String str) throws IOException {
        if (fatLfnDirectoryEntry.getName().equals(str)) {
            return;
        }
        removeEntry(fatLfnDirectoryEntry);
        fatLfnDirectoryEntry.setName(str, ShortNameGenerator.generateShortName(str, this.shortNameMap.keySet()));
        addEntry(fatLfnDirectoryEntry, fatLfnDirectoryEntry.getActualEntry());
        write();
    }

    void write() throws IOException {
        init();
        int entryCount = 0;
        boolean z = isRoot() && this.volumeLabel != null;
        Iterator<FatLfnDirectoryEntry> it = this.entries.iterator();
        while (it.hasNext()) {
            entryCount += it.next().getEntryCount();
        }
        if (z) {
            entryCount++;
        }
        long j = entryCount * 32;
        this.chain.setLength(j);
        ByteBuffer byteBufferAllocate = ByteBuffer.allocate((int) this.chain.getLength());
        byteBufferAllocate.order(ByteOrder.LITTLE_ENDIAN);
        if (z) {
            FatDirectoryEntry.createVolumeLabel(this.volumeLabel).serialize(byteBufferAllocate);
        }
        Iterator<FatLfnDirectoryEntry> it2 = this.entries.iterator();
        while (it2.hasNext()) {
            it2.next().serialize(byteBufferAllocate);
        }
        if (j % ((long) this.bootSector.getBytesPerCluster()) != 0 || j == 0) {
            byteBufferAllocate.put(new byte[32]);
        }
        byteBufferAllocate.flip();
        this.chain.write(0L, byteBufferAllocate);
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public boolean isRoot() {
        return this.entry == null;
    }

    String getVolumeLabel() {
        return this.volumeLabel;
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public FatFile createFile(String str) throws IOException {
        if (this.lfnMap.containsKey(str.toLowerCase(Locale.getDefault()))) {
            throw new IOException("Item already exists!");
        }
        init();
        ShortName shortNameGenerateShortName = ShortNameGenerator.generateShortName(str, this.shortNameMap.keySet());
        FatLfnDirectoryEntry fatLfnDirectoryEntryCreateNew = FatLfnDirectoryEntry.createNew(str, shortNameGenerateShortName);
        fatLfnDirectoryEntryCreateNew.setStartCluster(this.fat.alloc(new Long[0], 1)[0].longValue());
        Log.d(TAG, "adding entry: " + fatLfnDirectoryEntryCreateNew + " with short name: " + shortNameGenerateShortName);
        addEntry(fatLfnDirectoryEntryCreateNew, fatLfnDirectoryEntryCreateNew.getActualEntry());
        write();
        return FatFile.create(fatLfnDirectoryEntryCreateNew, this.blockDevice, this.fat, this.bootSector, this);
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public FatDirectory createDirectory(String str) throws IOException {
        if (this.lfnMap.containsKey(str.toLowerCase(Locale.getDefault()))) {
            throw new IOException("Item already exists!");
        }
        init();
        ShortName shortNameGenerateShortName = ShortNameGenerator.generateShortName(str, this.shortNameMap.keySet());
        FatLfnDirectoryEntry fatLfnDirectoryEntryCreateNew = FatLfnDirectoryEntry.createNew(str, shortNameGenerateShortName);
        fatLfnDirectoryEntryCreateNew.setDirectory();
        long jLongValue = this.fat.alloc(new Long[0], 1)[0].longValue();
        fatLfnDirectoryEntryCreateNew.setStartCluster(jLongValue);
        Log.d(TAG, "adding entry: " + fatLfnDirectoryEntryCreateNew + " with short name: " + shortNameGenerateShortName);
        addEntry(fatLfnDirectoryEntryCreateNew, fatLfnDirectoryEntryCreateNew.getActualEntry());
        write();
        FatDirectory fatDirectoryCreate = create(fatLfnDirectoryEntryCreateNew, this.blockDevice, this.fat, this.bootSector, this);
        fatDirectoryCreate.hasBeenInited = true;
        fatDirectoryCreate.entries = new ArrayList();
        FatLfnDirectoryEntry fatLfnDirectoryEntryCreateNew2 = FatLfnDirectoryEntry.createNew(null, new ShortName(".", ""));
        fatLfnDirectoryEntryCreateNew2.setDirectory();
        fatLfnDirectoryEntryCreateNew2.setStartCluster(jLongValue);
        FatLfnDirectoryEntry.copyDateTime(fatLfnDirectoryEntryCreateNew, fatLfnDirectoryEntryCreateNew2);
        fatDirectoryCreate.addEntry(fatLfnDirectoryEntryCreateNew2, fatLfnDirectoryEntryCreateNew2.getActualEntry());
        FatLfnDirectoryEntry fatLfnDirectoryEntryCreateNew3 = FatLfnDirectoryEntry.createNew(null, new ShortName("..", ""));
        fatLfnDirectoryEntryCreateNew3.setDirectory();
        fatLfnDirectoryEntryCreateNew3.setStartCluster(isRoot() ? 0L : fatLfnDirectoryEntryCreateNew.getStartCluster());
        FatLfnDirectoryEntry.copyDateTime(fatLfnDirectoryEntryCreateNew, fatLfnDirectoryEntryCreateNew3);
        fatDirectoryCreate.addEntry(fatLfnDirectoryEntryCreateNew3, fatLfnDirectoryEntryCreateNew3.getActualEntry());
        fatDirectoryCreate.write();
        return fatDirectoryCreate;
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void setLength(long j) {
        throw new UnsupportedOperationException("This is a directory!");
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public long getLength() {
        throw new UnsupportedOperationException("This is a directory!");
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public UsbFile search(String str) throws IOException {
        Log.d(TAG, "search file: " + str);
        init();
        int iIndexOf = str.indexOf("/");
        if (iIndexOf < 0) {
            Log.d(TAG, "search entry: " + str);
            FatLfnDirectoryEntry fatLfnDirectoryEntryFindEntry = findEntry(str);
            if (fatLfnDirectoryEntryFindEntry != null) {
                if (fatLfnDirectoryEntryFindEntry.isDirectory()) {
                    return create(fatLfnDirectoryEntryFindEntry, this.blockDevice, this.fat, this.bootSector, this);
                }
                return FatFile.create(fatLfnDirectoryEntryFindEntry, this.blockDevice, this.fat, this.bootSector, this);
            }
        } else {
            String strSubstring = str.substring(iIndexOf + 1);
            String strSubstring2 = str.substring(0, iIndexOf);
            Log.d(TAG, "search recursively " + strSubstring + " in " + strSubstring2);
            for (FatLfnDirectoryEntry fatLfnDirectoryEntry : this.entries) {
                if (fatLfnDirectoryEntry.isDirectory() && fatLfnDirectoryEntry.getName().equals(strSubstring2)) {
                    Log.d(TAG, "found " + strSubstring2);
                    return create(fatLfnDirectoryEntry, this.blockDevice, this.fat, this.bootSector, this).search(strSubstring);
                }
            }
        }
        Log.d(TAG, "not found " + str);
        return null;
    }

    private FatLfnDirectoryEntry findEntry(String str) {
        for (FatLfnDirectoryEntry fatLfnDirectoryEntry : this.entries) {
            if (fatLfnDirectoryEntry.getName().equals(str)) {
                return fatLfnDirectoryEntry;
            }
        }
        return null;
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public String getName() {
        FatLfnDirectoryEntry fatLfnDirectoryEntry = this.entry;
        return fatLfnDirectoryEntry != null ? fatLfnDirectoryEntry.getName() : "";
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void setName(String str) throws IOException {
        if (isRoot()) {
            throw new IllegalStateException("Cannot rename root dir!");
        }
        this.parent.renameEntry(this.entry, str);
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public long createdAt() {
        if (isRoot()) {
            throw new IllegalStateException("root dir!");
        }
        return this.entry.getActualEntry().getCreatedDateTime();
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public long lastModified() {
        if (isRoot()) {
            throw new IllegalStateException("root dir!");
        }
        return this.entry.getActualEntry().getLastModifiedDateTime();
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public long lastAccessed() {
        if (isRoot()) {
            throw new IllegalStateException("root dir!");
        }
        return this.entry.getActualEntry().getLastAccessedDateTime();
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public UsbFile getParent() {
        return this.parent;
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public String[] list() throws IOException {
        init();
        ArrayList arrayList = new ArrayList(this.entries.size());
        for (int i = 0; i < this.entries.size(); i++) {
            String name = this.entries.get(i).getName();
            if (!name.equals(".") && !name.equals("..")) {
                arrayList.add(name);
            }
        }
        return (String[]) arrayList.toArray(new String[arrayList.size()]);
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public UsbFile[] listFiles() throws IOException {
        init();
        ArrayList arrayList = new ArrayList(this.entries.size());
        for (int i = 0; i < this.entries.size(); i++) {
            FatLfnDirectoryEntry fatLfnDirectoryEntry = this.entries.get(i);
            String name = fatLfnDirectoryEntry.getName();
            if (!name.equals(".") && !name.equals("..")) {
                if (fatLfnDirectoryEntry.isDirectory()) {
                    arrayList.add(create(fatLfnDirectoryEntry, this.blockDevice, this.fat, this.bootSector, this));
                } else {
                    arrayList.add(FatFile.create(fatLfnDirectoryEntry, this.blockDevice, this.fat, this.bootSector, this));
                }
            }
        }
        return (UsbFile[]) arrayList.toArray(new UsbFile[arrayList.size()]);
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void read(long j, ByteBuffer byteBuffer) throws IOException {
        throw new UnsupportedOperationException("This is a directory!");
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void write(long j, ByteBuffer byteBuffer) throws IOException {
        throw new UnsupportedOperationException("This is a directory!");
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void flush() throws IOException {
        throw new UnsupportedOperationException("This is a directory!");
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile, java.io.Closeable, java.lang.AutoCloseable
    public void close() throws IOException {
        throw new UnsupportedOperationException("This is a directory!");
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void moveTo(UsbFile usbFile) throws IOException {
        if (isRoot()) {
            throw new IllegalStateException("cannot move root dir!");
        }
        if (!usbFile.isDirectory()) {
            throw new IllegalStateException("destination cannot be a file!");
        }
        if (!(usbFile instanceof FatDirectory)) {
            throw new IllegalStateException("cannot move between different filesystems!");
        }
        FatDirectory fatDirectory = (FatDirectory) usbFile;
        if (fatDirectory.lfnMap.containsKey(this.entry.getName().toLowerCase(Locale.getDefault()))) {
            throw new IOException("item already exists in destination!");
        }
        init();
        fatDirectory.init();
        this.parent.removeEntry(this.entry);
        FatLfnDirectoryEntry fatLfnDirectoryEntry = this.entry;
        fatDirectory.addEntry(fatLfnDirectoryEntry, fatLfnDirectoryEntry.getActualEntry());
        this.parent.write();
        fatDirectory.write();
        this.parent = fatDirectory;
    }

    void move(FatLfnDirectoryEntry fatLfnDirectoryEntry, UsbFile usbFile) throws IOException {
        if (!usbFile.isDirectory()) {
            throw new IllegalStateException("destination cannot be a file!");
        }
        if (!(usbFile instanceof FatDirectory)) {
            throw new IllegalStateException("cannot move between different filesystems!");
        }
        FatDirectory fatDirectory = (FatDirectory) usbFile;
        if (fatDirectory.lfnMap.containsKey(fatLfnDirectoryEntry.getName().toLowerCase(Locale.getDefault()))) {
            throw new IOException("item already exists in destination!");
        }
        init();
        fatDirectory.init();
        removeEntry(fatLfnDirectoryEntry);
        fatDirectory.addEntry(fatLfnDirectoryEntry, fatLfnDirectoryEntry.getActualEntry());
        write();
        fatDirectory.write();
    }

    @Override // com.github.mjdev.libaums.fs.UsbFile
    public void delete() throws IOException {
        if (isRoot()) {
            throw new IllegalStateException("Root dir cannot be deleted!");
        }
        init();
        for (UsbFile usbFile : listFiles()) {
            usbFile.delete();
        }
        this.parent.removeEntry(this.entry);
        this.parent.write();
        this.chain.setLength(0L);
    }
}
