package app.shr3d;

import android.app.Activity;
import android.content.ClipData;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.Manifest;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends android.app.NativeActivity {
  static {
    System.loadLibrary("openxr_loader");
    System.loadLibrary("shr3d");
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getPermission(this);

    SuperpoweredUSBAudio usbAudio = new SuperpoweredUSBAudio(this);
    usbAudio.check();
  }

  private void getPermission(Activity activity) {
    String[] checkList = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO};
    List<String> needRequestList = checkPermission(activity, checkList);
    if (needRequestList.isEmpty()) {
      //Log.i("TAG", "No need to apply for storage permission!");
    } else {
      requestPermission(activity, needRequestList.toArray(new String[needRequestList.size()]));
    }
  }

  private List<String> checkPermission(Context context, String[] checkList) {
    List<String> list = new ArrayList<>();
    for (int i = 0; i < checkList.length; i++) {
      if (PackageManager.PERMISSION_GRANTED != context.checkSelfPermission(checkList[i])) {
        list.add(checkList[i]);
      }
    }
    return list;
  }

  private void requestPermission(Activity activity, String requestPermissionList[]) {
    activity.requestPermissions(requestPermissionList, 100);
  }

  public static native void recordAudioPermissionResult(boolean granted);

  public static native void openFileDialogResult(String path);


  @Override
  public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == 100) {
      for (int i = 0; i < permissions.length; i++) {
        if (permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
          if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
            //Log.i("TAG", "Successfully applied for storage permission!");
          } else {
            //Log.e("TAG", "Failed to apply for storage permission!");
          }
        }
        else if (permissions[i].equals(Manifest.permission.RECORD_AUDIO))
        {
          if (grantResults[i] == PackageManager.PERMISSION_GRANTED)
            recordAudioPermissionResult(true);
        }
      }
    }
  }

  private String getFileNameAndroidV10(Uri uri)
  {
    Cursor cursor = null;
    String[] projection = {
            MediaStore.MediaColumns.DISPLAY_NAME
    };

    try
    {
      cursor = getContentResolver().query(uri, projection, null, null, null);
      if (cursor != null && cursor.moveToFirst())
      {
        int index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME);
        return cursor.getString(index);
      }
    }
    finally
    {
      if (cursor != null)
      {
        cursor.close();
      }
    }
    return null;
  }

  private void addFileFromPicker(Uri uri)
  {
    InputStream inputStream = null;
    try {
      inputStream = getContentResolver().openInputStream(uri);
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    }

    String fileName = new File(uri.getPath()).getName();

    if (fileName.startsWith("msf:")) // On Android 10 you don't get the real filename. This will fix it.
      fileName = getFileNameAndroidV10(uri);

    File dataDirectory = getApplicationContext().getDataDir();

    File destinationFile;
    if (fileName.endsWith(".psarc"))
      destinationFile = new File(dataDirectory.getAbsoluteFile() + "/psarc/" + fileName);
    else if (fileName.endsWith(".shred"))
      destinationFile = new File(dataDirectory.getAbsoluteFile() + "/shred/" + fileName);
    else if (fileName.endsWith(".nam") || fileName.endsWith(".wav"))
      destinationFile = new File(dataDirectory.getAbsoluteFile() + "/nam/" + fileName);
    else if (fileName.endsWith(".stage_a"))
      destinationFile = new File(dataDirectory.getAbsoluteFile() + "/stage/" + fileName);
    else if (fileName.endsWith(".astc") || fileName.endsWith(".astc6"))
      destinationFile = new File(dataDirectory.getAbsoluteFile() + "/skybox/" + fileName);
    else
      return;

    try {
      OutputStream outputStream = new FileOutputStream(destinationFile);

      byte[] buffer = new byte[1024];
      int length;

      try {
        while ((length = inputStream.read(buffer)) > 0) {
          try {
            outputStream.write(buffer, 0, length);
          } catch (FileNotFoundException e)
          {
            assert(false);
          }
        }
      } catch (IOException e)
      {
        assert(false);
      }
    } catch (FileNotFoundException e)
    {
      assert(false);
    }

    openFileDialogResult(destinationFile.getPath());
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
    assert(requestCode == 1); // expand if needed
    if (resultCode == Activity.RESULT_OK)
    {
      if (resultData.getClipData() != null) // Handle multiple selection
      {
        ClipData clipData = resultData.getClipData();
        int itemCount = clipData.getItemCount();

        for (int i = 0; i < itemCount; i++)
        {
          Uri uri = clipData.getItemAt(i).getUri();
          addFileFromPicker(uri);
        }
      }
      else // Handle single selection
      {
        Uri uri = resultData.getData();
        addFileFromPicker(uri);
      }
    }
  }
}
