package com.lemenzo.messenger.mms;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

public final class MmsFileProvider extends ContentProvider {
    public static final String AUTHORITY = "com.lemenzo.messenger.mmsfile";
    private static final String DIR = "raw_mms";

    @Override
    public boolean onCreate() {
        File dir = directory();
        return dir.exists() || dir.mkdirs();
    }

    public static Uri createUri(android.content.Context context, String prefix) {
        File dir = new File(context.getCacheDir(), DIR);
        if (!dir.exists()) dir.mkdirs();
        String safePrefix = prefix == null ? "mms" : prefix.replaceAll("[^A-Za-z0-9_-]", "_");
        String name = safePrefix + "_" + UUID.randomUUID() + ".pdu";
        return new Uri.Builder()
                .scheme("content")
                .authority(AUTHORITY)
                .appendPath(name)
                .build();
    }

    public static File fileFor(android.content.Context context, Uri uri)
            throws FileNotFoundException {
        if (uri == null || !AUTHORITY.equals(uri.getAuthority())) {
            throw new FileNotFoundException("Invalid MMS file URI");
        }
        String name = uri.getLastPathSegment();
        if (name == null || !name.matches("[A-Za-z0-9_-]+\\.pdu")) {
            throw new FileNotFoundException("Invalid MMS file name");
        }

        File dir = new File(context.getCacheDir(), DIR);
        File file = new File(dir, name);
        try {
            String root = dir.getCanonicalPath() + File.separator;
            String child = file.getCanonicalPath();
            if (!child.startsWith(root)) {
                throw new FileNotFoundException("MMS path escaped cache directory");
            }
        } catch (IOException e) {
            throw new FileNotFoundException("Unable to validate MMS path");
        }
        return file;
    }

    public static void delete(android.content.Context context, Uri uri) {
        try {
            File f = fileFor(context, uri);
            if (f.exists()) f.delete();
        } catch (FileNotFoundException ignored) {
        }
    }

    private File directory() {
        return new File(getContext().getCacheDir(), DIR);
    }

    @Override
    public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
        File file = fileFor(getContext(), uri);
        File parent = file.getParentFile();
        if (!parent.exists()) parent.mkdirs();

        int parcelMode;
        if ("r".equals(mode)) {
            parcelMode = ParcelFileDescriptor.MODE_READ_ONLY;
        } else {
            parcelMode = ParcelFileDescriptor.MODE_WRITE_ONLY
                    | ParcelFileDescriptor.MODE_CREATE
                    | ParcelFileDescriptor.MODE_TRUNCATE;
        }
        return ParcelFileDescriptor.open(file, parcelMode);
    }

    @Override public Cursor query(Uri uri, String[] projection, String selection,
            String[] selectionArgs, String sortOrder) { return null; }
    @Override public String getType(Uri uri) { return "application/vnd.wap.mms-message"; }
    @Override public Uri insert(Uri uri, ContentValues values) { return null; }
    @Override public int delete(Uri uri, String selection, String[] selectionArgs) { return 0; }
    @Override public int update(Uri uri, ContentValues values, String selection,
            String[] selectionArgs) { return 0; }
}
