package com.volcengine.reactnative.veplayer;

import android.os.Build;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceView;
import android.view.TextureView;
import android.view.View;
import androidx.annotation.Nullable;

import java.util.HashMap;

import com.ss.ttvideoengine.PreloaderURLItem;
import com.ss.ttvideoengine.PreloaderVidItem;
import com.ss.ttvideoengine.PreloaderVideoModelItem;
import com.ss.ttvideoengine.Resolution;
import com.ss.ttvideoengine.TTVideoEngine;
import com.ss.ttvideoengine.abr.TTVideoABRConfig;
import com.ss.ttvideoengine.abr.TTVideoABRStartupConfig;
import com.ss.ttvideoengine.abr.TTVideoABRStrategy;
import com.ss.ttvideoengine.abr.TTVideoABRStartupConfig.TTVideoABRStartupResolutionListener;
import com.volcengine.VolcApiEngine.view.VolcViewManager;

// Helper for JS to setView
public class VePlayerHelper {
  private static final String TAG = "VePlayerHelper";
  private static final HashMap<String, TTVideoEngine> playerMap = new HashMap<>();
  
  static public void engineBindView(TTVideoEngine ttVideoEngine, Object arg) {
    if (arg == null) {
      return;
    }
    
    if (!(arg instanceof View)) {
      return;
    }
    
    View view = (View)  arg;
    VeplayerView veplayerView = (VeplayerView)view.getParent();
    veplayerView.setPlayerEngine(ttVideoEngine);
    
//     ttVideoEngine.setIntOption(TTVideoEngine.PLAYER_OPTION_USE_TEXTURE_RENDER, 1);
    
    switch (veplayerView.viewKind) {
      case "TextureView": {
        // Check if TextureView is available
        if (veplayerView.subView instanceof TextureView) {
          TextureView textureView = (TextureView) veplayerView.subView;
          if (!textureView.isAvailable()) {
            Log.e(TAG, "TextureView is not available, cannot set surface");
            throw new IllegalStateException("TextureView is not available, cannot set surface");
          }
        }
        
        var surfaceTexture = veplayerView.getSurfaceTexture();
        if (surfaceTexture == null) {
          Log.e(TAG, "SurfaceTexture is null, cannot set surface");
          throw new IllegalStateException("SurfaceTexture is null, cannot set surface");
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
          if (surfaceTexture.isReleased()) {
            Log.e(TAG, "SurfaceTexture is released, cannot set surface");
            throw new IllegalStateException("SurfaceTexture is released, cannot set surface");
          }
        }
        Surface surface = new Surface(surfaceTexture);
        try {
          ttVideoEngine.setSurface(surface);
          return;
        } catch (Exception e) {
          Log.w(TAG, "Failed to setSurface for ttVideoEngine: " + e.getMessage());
          return;
        }
      }
      case "SurfaceView": {
        var surfaceHolder = ((SurfaceView) veplayerView.subView).getHolder();
        ttVideoEngine.setSurfaceHolder(surfaceHolder);
        return;
      }
    }
  }
  
  static public boolean viewHasRegister(String viewId) {
    return VolcViewManager.getViewById(viewId) != null;
  }
  
  public static void setPlayer(String viewId, TTVideoEngine pusher) {
    playerMap.put(viewId, pusher);
  }

  public static void removePlayer(String viewId) {
    playerMap.remove(viewId);
  }

  public static TTVideoEngine getPlayer(String viewId) {
      return playerMap.get(viewId);
  }
  
  
  public static void addTaskByVidItem(PreloaderVidItem item) {
    TTVideoEngine.addTask(item);
  }
  
  public static void addTaskByUrlItem(PreloaderURLItem item) {
    TTVideoEngine.addTask(item);
  }
  
  public static void addTaskByVideoModelItem(PreloaderVideoModelItem item) {
    TTVideoEngine.addTask(item);
  }

  public static void setPreloaderVidItemResolution(PreloaderVidItem item, Resolution resolution, TTVideoABRStartupConfig abrConfig) {
    if (item == null) {
      return;
    }
    if (resolution == null) {
      return;
    }
    item.setFetchEndListener((videoModel, error) -> {
      if (videoModel == null) {
        return;
      }
      if (error != null) {
        return;
      }
      if(resolution == Resolution.Auto && abrConfig != null) {
        item.mResolution = TTVideoABRStrategy.preloadSelect(videoModel, abrConfig);
      } else {
        item.mResolution = resolution;
      }
    });
  }

  public static void setPreloaderVideoModelItemResolution(PreloaderVideoModelItem item, Resolution resolution, TTVideoABRStartupConfig abrConfig) {
    if (item == null) {
      return;
    }
    if (resolution == null) {
      return;
    }
    if (resolution == Resolution.Auto && abrConfig != null) {
      item.mResolution = TTVideoABRStrategy.preloadSelect(item.mVideoModel, abrConfig);
    } else {
      item.mResolution = resolution;
    }
  }

  public static TTVideoABRStartupConfig createStartupConfig(
      @Nullable Resolution defaultResolution,
      @Nullable Resolution wifiMaxResolution,
      @Nullable Resolution mobileMaxResolution,
      int screenWidth,
      int screenHeight,
      int displayWidth,
      int displayHeight,
      @Nullable Resolution userSelectedResolution,
      @Nullable TTVideoABRStartupResolutionListener listener
      ) {
    TTVideoABRStartupConfig config = new TTVideoABRStartupConfig();
    if (defaultResolution != null) {
      config.defaultResolution = defaultResolution;
    }
    if (wifiMaxResolution != null) {
      config.wifiMaxResolution = wifiMaxResolution;
    }
    if (mobileMaxResolution != null) {
      config.mobileMaxResolution = mobileMaxResolution;
    }
    if (screenWidth != 0) {
      config.screenWidth = screenWidth;
    }
    if (screenHeight != 0) {
      config.screenHeight = screenHeight;
    }
    if (displayWidth != 0) {
      config.displayWidth = displayWidth;
    }
    if (displayHeight != 0) {
      config.displayHeight = displayHeight;
    }
    if (userSelectedResolution != null) {
      config.userSelectedResolution = userSelectedResolution;
    }

    if (listener != null) {
      config.mListener = listener;
    }

    return config;
  }


  public static TTVideoABRConfig createABRConfig(
      @Nullable Resolution defaultResolution,
      @Nullable Resolution wifiMaxResolution,
      @Nullable Resolution mobileMaxResolution,
      int screenWidth,
      int screenHeight,
      int displayWidth,
      int displayHeight
      ) {
    TTVideoABRConfig config = new TTVideoABRConfig();
    if (defaultResolution != null) {
      config.defaultResolution = defaultResolution;
    }
    if (wifiMaxResolution != null) {
      config.wifiMaxResolution = wifiMaxResolution;
    }
    if (mobileMaxResolution != null) {
      config.mobileMaxResolution = mobileMaxResolution;
    }
    if (screenWidth != 0) {
      config.screenWidth = screenWidth;
    }
    if (screenHeight != 0) {
      config.screenHeight = screenHeight;
    }
    if (displayWidth != 0) {
      config.displayWidth = displayWidth;
    }
    if (displayHeight != 0) {
      config.displayHeight = displayHeight;
    }

    return config;
  }

}
