package com.datarecovery.master.utils.xfile;

import android.content.Context;
import android.net.Uri;
import android.os.Build;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLConnection;
import java.nio.file.Files;

public class XPathFile extends BaseXFile {

    private final Context context;
    private final File file;

    public XPathFile(Context context, String path) {
        this(context, new File(path));
    }

    public XPathFile(Context context, File file) {
        this.context = context;
        this.file = file;
    }

    public XPathFile(Context context, File dir, String child) {
        this(context, new File(dir, child));
    }

    @Override
    public String getName() throws Exception {
        return file.getName();
    }

    @Override
    public String getPath() {
        return file.getPath();
    }

    @Override
    public String getMineType() {
        return URLConnection.guessContentTypeFromName(file.getName());
    }

    @Override
    public Uri getUri() throws Exception {
        return Uri.fromFile(file);
    }


    @Override
    public boolean isDirectory() {
        return file.isDirectory();
    }

    @Override
    public XFile[] listFiles() {
        File[] files = file.listFiles();
        if (files == null) {
            return null;
        }
        XFile[] xFiles = new XFile[files.length];
        for (int i = 0; i < files.length; i++) {
            xFiles[i] = new XPathFile(context, files[i]);
        }
        return xFiles;
    }

    @Override
    public boolean exists() {
        return file.exists();
    }

    @Override
    public boolean delete() {
        return file.delete();
    }

    @Override
    public long length() {
        return file.length();
    }

    @Override
    public long lastModified() throws Exception {
        return file.lastModified();
    }

    @Override
    public InputStream newInputStream() throws Exception {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return Files.newInputStream(file.toPath());
        } else {
            return new FileInputStream(file);
        }
    }
}
