/*
 * Copyright (c) 2016, The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.android.car.stream.media;

import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.VectorDrawable;
import android.view.KeyEvent;
import android.widget.RemoteViews;
import com.android.car.stream.MediaPlaybackExtension;
import com.android.car.stream.R;
import com.android.car.stream.StreamCard;
import com.android.car.stream.StreamConstants;
import com.android.car.stream.StreamServiceConstants;

/**
 * A converter that creates a {@link StreamCard} for currently playing media.
 */
public class MediaConverter {
    private final PendingIntent mGotoMediaFacetAction;
    private final PendingIntent mPauseAction;
    private final PendingIntent mSkipToNextAction;
    private final PendingIntent mSkipToPreviousAction;
    private final PendingIntent mPlayAction;
    private final PendingIntent mStopAction;

    private Bitmap mPlayIcon;
    private Bitmap mPauseIcon;

    public MediaConverter(Context context) {
        String mediaPackage = context.getString(R.string.car_media_component_package);
        mGotoMediaFacetAction = createGoToMediaFacetIntent(context, mediaPackage);

        mPauseAction = getMediaActionIntent(context,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PAUSE),
                KeyEvent.KEYCODE_MEDIA_PAUSE /* requestCode */);

        mSkipToNextAction = getMediaActionIntent(context,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD),
                KeyEvent.KEYCODE_MEDIA_SKIP_FORWARD /* requestCode */);

        mSkipToPreviousAction = getMediaActionIntent(context,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_SKIP_BACKWARD),
                KeyEvent.KEYCODE_MEDIA_SKIP_BACKWARD /* requestCode */);


        mPlayAction = getMediaActionIntent(context,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_PLAY),
                KeyEvent.KEYCODE_MEDIA_PLAY /* requestCode */);

        mStopAction = getMediaActionIntent(context,
                new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_MEDIA_STOP),
                KeyEvent.KEYCODE_MEDIA_STOP /* requestCode */);

        int iconSize = context.getResources()
                .getDimensionPixelSize(R.dimen.stream_card_secondary_icon_dimen);
        mPlayIcon = getBitmap((VectorDrawable)
                context.getDrawable(R.drawable.ic_play_arrow), iconSize, iconSize);
        mPauseIcon = getBitmap((VectorDrawable)
                context.getDrawable(R.drawable.ic_pause), iconSize, iconSize);
    }

    public StreamCard convert(
            String title,
            String subtitle,
            Bitmap albumArt,
            int appAccentColor,
            String appName,
            boolean canSkipToNext,
            boolean canSkipToPrevious,
            boolean hasPause,
            boolean isPlaying) {

        StreamCard.Builder builder = new StreamCard.Builder(StreamConstants.CARD_TYPE_MEDIA,
                StreamConstants.MEDIA_CARD_ID, System.currentTimeMillis());
        builder.setClickAction(mGotoMediaFacetAction);
        builder.setPrimaryText(title);
        builder.setSecondaryText(subtitle);
        Bitmap icon = isPlaying ? mPlayIcon : mPauseIcon;
        builder.setPrimaryIcon(icon);

        MediaPlaybackExtension extension = new MediaPlaybackExtension(title, subtitle, albumArt,
                appAccentColor, canSkipToNext, canSkipToPrevious, hasPause, isPlaying, appName,
                mStopAction, mPauseAction, mPlayAction, mSkipToNextAction, mSkipToPreviousAction);

        builder.setCardExtension(extension);
        return builder.build();
    }

    /**
     * Attaches a {@link PendingIntent} to the given {@link RemoteViews}. The PendingIntent will
     * send the user to the CarMediaApp when touched. Note that this does not resolve to the
     * application currently in the media card; instead, it just opens the last music app. For
     * example, if the card is generated by Google Play Music, but the last opened music app
     * was Spotify, then Spotify will open when the music card is tapped.
     */
    private PendingIntent createGoToMediaFacetIntent(Context context, String mediaPackage) {
        Intent intent = context.getPackageManager().getLaunchIntentForPackage(mediaPackage);
        intent.addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT);

        return PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }

    private PendingIntent getMediaActionIntent(Context context, KeyEvent ke, int requestCode) {
        Intent i = new Intent(Intent.ACTION_MEDIA_BUTTON);
        i.setPackage(context.getPackageName());
        i.putExtra(Intent.EXTRA_KEY_EVENT, ke);

        PendingIntent pendingIntent =
                PendingIntent.getBroadcast(
                        context,
                        requestCode,
                        i,
                        PendingIntent.FLAG_CANCEL_CURRENT
                );
        return pendingIntent;
    }

    private static Bitmap getBitmap(VectorDrawable vectorDrawable, int width, int height) {
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        vectorDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
        vectorDrawable.draw(canvas);
        return bitmap;
    }
}
