/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.streams.youtube.provider;

import org.apache.streams.config.ComponentConfigurator;
import org.apache.streams.config.StreamsConfiguration;
import org.apache.streams.config.StreamsConfigurator;
import org.apache.streams.core.StreamsDatum;
import org.apache.streams.google.gplus.configuration.UserInfo;
import org.apache.streams.jackson.StreamsJacksonMapper;
import org.apache.streams.util.api.requests.backoff.BackOffStrategy;
import org.apache.streams.youtube.YoutubeConfiguration;
import org.apache.streams.youtube.YoutubeUserActivityProviderConfiguration;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.api.services.youtube.YouTube;
import com.google.common.base.Preconditions;
import com.google.common.util.concurrent.Uninterruptibles;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import com.typesafe.config.ConfigParseOptions;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * Retrieve recent activity from a list of user ids or names.
 */
public class YoutubeUserActivityProvider extends YoutubeProvider {

  public YoutubeUserActivityProvider() {
    super();
  }

  public YoutubeUserActivityProvider(YoutubeConfiguration config) {
    super(config);
  }

  /**
   * To use from command line:
   * <p>
   * <p></p>
   * Supply (at least) the following required configuration in application.conf:
   * <p>
   * <p></p>
   * youtube.oauth.pathToP12KeyFile
   * youtube.oauth.serviceAccountEmailAddress
   * youtube.apiKey
   * youtube.youtubeUsers
   * <p>
   * <p></p>
   * Launch using:
   * <p>
   * <p></p>
   * mvn exec:java -Dexec.mainClass=org.apache.streams.youtube.provider.YoutubeUserActivityProvider -Dexec.args="application.conf tweets.json"
   *
   * @param args args
   * @throws Exception Exception
   */
  public static void main(String[] args) throws Exception {

    Preconditions.checkArgument(args.length >= 2);

    String configfile = args[0];
    String outfile = args[1];

    File file = new File(configfile);
    assert (file.exists());

    Config conf = ConfigFactory.parseFileAnySyntax(file, ConfigParseOptions.defaults().setAllowMissing(false));
    StreamsConfigurator.addConfig(conf);

    StreamsConfiguration streamsConfiguration = StreamsConfigurator.detectConfiguration();
    YoutubeUserActivityProviderConfiguration config = new ComponentConfigurator<>(YoutubeUserActivityProviderConfiguration.class).detectConfiguration();
    YoutubeUserActivityProvider provider = new YoutubeUserActivityProvider(config);

    ObjectMapper mapper = StreamsJacksonMapper.getInstance();

    PrintStream outStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(outfile)));
    provider.prepare(config);
    provider.startStream();
    do {
      Uninterruptibles.sleepUninterruptibly(streamsConfiguration.getBatchFrequencyMs(), TimeUnit.MILLISECONDS);
      Iterator<StreamsDatum> iterator = provider.readCurrent().iterator();
      while (iterator.hasNext()) {
        StreamsDatum datum = iterator.next();
        String json;
        try {
          if (datum.getDocument() instanceof String) {
            json = (String) datum.getDocument();
          } else {
            json = mapper.writeValueAsString(datum.getDocument());
          }
          outStream.println(json);
        } catch (JsonProcessingException ex) {
          System.err.println(ex.getMessage());
        }
      }
    }
    while (provider.isRunning());
    provider.cleanUp();
    outStream.flush();
  }

  @Override
  protected Runnable getDataCollector(BackOffStrategy strategy, BlockingQueue<StreamsDatum> queue, YouTube youtube, UserInfo userInfo) {
    return new YoutubeUserActivityCollector(youtube, queue, strategy, userInfo, config);
  }
}
