/*
 * ************************************************************************
 *
 * ADOBE SYSTEMS INCORPORATED
 * Copyright 2015 Adobe Systems Incorporated
 * All Rights Reserved.
 * NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance with the
 * terms of the Adobe license agreement accompanying it.  If you have received this file from a
 * source other than Adobe, then your use, modification, or distribution of it requires the prior
 * written permission of Adobe.
 *
 **************************************************************************
 */

package com.adobe.primetime.reference.advertising;

import android.content.Context;

import com.adobe.mediacore.MediaPlayerItem;
import com.adobe.mediacore.MediaPlayerItemConfig;
import com.adobe.mediacore.metadata.AdSignalingMode;
import com.adobe.mediacore.metadata.TimedMetadata;
import com.adobe.mediacore.timeline.Opportunity;
import com.adobe.mediacore.timeline.Placement;
import com.adobe.mediacore.metadata.AdvertisingMetadata;
import com.adobe.mediacore.timeline.generators.OpportunityGenerator;
import com.adobe.mediacore.timeline.generators.OpportunityGeneratorClient;
import com.adobe.mediacore.utils.TimeRange;

public class CustomOpportunityGenerator implements OpportunityGenerator {

    public CustomOpportunityGenerator()
    {}

    public void configure(MediaPlayerItem item, Context context, OpportunityGeneratorClient client, AdSignalingMode mode, long playhead, TimeRange playbackRange)
    {
        MediaPlayerItemConfig itemConfig = item.getConfig();

        if (itemConfig == null || itemConfig.getAdvertisingMetadata() == null) {
            // no ad metadata, no ads
            return;
        }

        AdvertisingMetadata metadata = item.getConfig().getAdvertisingMetadata();

        if (item.isLive() && !metadata.hasLivePreroll())
        {
            // live pre-roll disabled so do not process initial opportunity
            return;
        }

        if (mode == AdSignalingMode.CUSTOM_RANGES)
        {
            // don't override custom ad ranges
            return;
        }

        Placement.Type pType = (mode == AdSignalingMode.MANIFEST_CUES) ? Placement.Type.PRE_ROLL : Placement.Type.SERVER_MAP;
        Placement.Mode pMode = Placement.Mode.DEFAULT;
        Placement placement = new Placement(pType, playhead, Placement.UNKNOWN_DURATION, pMode);

        Opportunity opportunity = new Opportunity("initialOpportunity", placement, metadata, null);

        client.resolve(opportunity);
    }

    public void update(long playhead, TimeRange playbackRange) {

    }

    public void cleanup() {

    }
}
