/**
 * $URL: $
 * DAAND
 * Copyright (C) 2004 - 2013, INSIDE Secure BV.  All rights reserved.
 */
package com.insidesecure.drm.android.reference.customdata.file;

import android.util.Log;
import com.insidesecure.drm.android.reference.*;
import com.insidesecure.drm.android.reference.customdata.CustomDataProvider;

import java.io.*;
import java.util.regex.*;

public class FileCustomDataProvider implements CustomDataProvider
{
    private static final String TAG = "FileCustomDataProvider";

    private static final Pattern FILE_CUSTOM_DATA_VALUE_PATTERN = Pattern.compile("<CustomDataParameters><FilePath>(.*)</FilePath></CustomDataParameters>");
    public static String DEFAULT_FILE_PATH = Constants.CONFIGURATION_CDESC_PATH + Constants.CONFIGURATION_CUSTOM_DATA_FILE_NAME;

    public String getCustomData(String parametersString) throws Exception
    {
        if (parametersString == null)
        {
            parametersString = "<CustomDataParameters><FilePath>" + DEFAULT_FILE_PATH + "</FilePath></CustomDataParameters>";
        }
        final Matcher matcher = FILE_CUSTOM_DATA_VALUE_PATTERN.matcher(parametersString);
        if (matcher.matches())
        {
            return getCustomDataInternal(matcher.group(1));
        }
        return null;
    }

    private String getCustomDataInternal(String filePath) throws IOException
    {
        log("Looking for custom data in file " + filePath);
        File f = new File(filePath);
        if (!f.exists())
        {
            log("File " + filePath + " doesn't exist, trying the default file: " + DEFAULT_FILE_PATH);
            f = new File(DEFAULT_FILE_PATH);
            if (!f.exists())
            {
                log("The default file: " + DEFAULT_FILE_PATH + " doesn't exist, returning NULL.");
                return null;
            }
        }

        final BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
        try
        {
            final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Tools.copyStream(bis, outputStream);
            outputStream.flush();
            return new String(outputStream.toByteArray());
        }
        finally
        {
            bis.close();
        }

    }

    private void log(final String s)
    {
        try
        {
            Log.d(TAG, s);
        }
        catch (Exception e)
        {
            // Ignore this since it may fail during tests etc ...
        }
    }


}
