/*
 * Copyright (C) 2020 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 "SkAndroidCodec.h"
#include "SkBitmap.h"
#include "SkCanvas.h"
#include "SkData.h"
#include "SkSurface.h"

#include "../includes/memutils.h"
#include <fstream>
#include <iostream>

#define SAMPLE_SIZE 6
char enable_selective_overload = ENABLE_NONE;

int decode(sk_sp<SkData> bytes, uint8_t sampleSize) {
  auto codec = SkAndroidCodec::MakeFromData(bytes);
  if (!codec) {
    return EXIT_FAILURE;
  }

  auto size = codec->getSampledDimensions(sampleSize);
  auto info = SkImageInfo::MakeN32Premul(size);
  SkBitmap bm;
  if (!bm.tryAllocPixels(info)) {
    return EXIT_FAILURE;
  }

  SkAndroidCodec::AndroidOptions options;
  options.fSampleSize = sampleSize;

  codec->getAndroidPixels(bm.info(), bm.getPixels(), bm.rowBytes(), &options);
  return EXIT_SUCCESS;
}

int main(int argc, char **argv) {
  if (argc != 2) {
    return EXIT_FAILURE;
  }
  std::ifstream inFile(argv[1]);
  if (!inFile) {
    return EXIT_FAILURE;
  }
  inFile.seekg(0, inFile.end);
  size_t size = inFile.tellg();
  if (size < 1) {
    inFile.close();
    return EXIT_FAILURE;
  }
  inFile.seekg(0, inFile.beg);
  uint8_t *data = (uint8_t *)malloc(size);
  if (!data) {
    return EXIT_FAILURE;
  }
  inFile.read(reinterpret_cast<char *>(data), size);
  auto bytes = SkData::MakeWithoutCopy(data, size);
  bytes = SkData::MakeSubset(bytes.get(), 1, size - 1);
  enable_selective_overload = ENABLE_ALL;
  int ret = decode(bytes, SAMPLE_SIZE);
  enable_selective_overload = ENABLE_NONE;
  inFile.close();
  free(data);
  return ret;
}
