package com.example.sjkbf.util;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * JavaFX视频播放器 - 用于测试服务端视频流
 */
public class JavaFXVideoPlayer extends Application {

    private MediaPlayer mediaPlayer;
    private MediaView mediaView;
    private Label statusLabel;
    private ProgressBar progressBar;
    private TextField projectField;
    private TextField videoNameField;
    private TextField serverUrlField;
    private Button playButton;
    private Button pauseButton;
    private Button stopButton;
    private Slider volumeSlider;
    private Slider seekSlider;
    private DoubleProperty playbackRate;
    
    private static final String DEFAULT_SERVER = "http://localhost:8651";

    @Override
    public void start(Stage primaryStage) {
        playbackRate = new SimpleDoubleProperty(1.0);
        
        // 创建UI组件
        createUIComponents();
        
        // 布局
        VBox root = createLayout();
        
        // 场景
        Scene scene = new Scene(root, 1000, 700);
        scene.getStylesheets().add(getClass().getResource("/styles.css").toExternalForm());
        
        // 舞台设置
        primaryStage.setTitle("视频流测试播放器");
        primaryStage.setScene(scene);
        primaryStage.setOnCloseRequest(event -> cleanup());
        primaryStage.show();
    }

    private void createUIComponents() {
        // 输入字段
        serverUrlField = new TextField(DEFAULT_SERVER);
        serverUrlField.setPromptText("服务器地址");
        
        projectField = new TextField("战令");
        projectField.setPromptText("项目名称");
        
        videoNameField = new TextField("2");
        videoNameField.setPromptText("视频名称");

        // 控制按钮
        playButton = new Button("播放");
        playButton.setOnAction(e -> playVideo());
        
        pauseButton = new Button("暂停");
        pauseButton.setOnAction(e -> pauseVideo());
        pauseButton.setDisable(true);
        
        stopButton = new Button("停止");
        stopButton.setOnAction(e -> stopVideo());
        stopButton.setDisable(true);

        // 媒体视图
        mediaView = new MediaView();
        mediaView.setFitWidth(800);
        mediaView.setFitHeight(450);
        mediaView.setPreserveRatio(true);

        // 进度条和滑块
        progressBar = new ProgressBar(0);
        progressBar.setPrefWidth(800);
        
        seekSlider = new Slider(0, 100, 0);
        seekSlider.setPrefWidth(800);
        seekSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (seekSlider.isValueChanging() && mediaPlayer != null) {
                Duration duration = mediaPlayer.getTotalDuration();
                if (duration != null) {
                    mediaPlayer.seek(duration.multiply(newVal.doubleValue() / 100.0));
                }
            }
        });

        // 音量控制
        volumeSlider = new Slider(0, 100, 50);
        volumeSlider.setPrefWidth(150);
        volumeSlider.valueProperty().addListener((obs, oldVal, newVal) -> {
            if (mediaPlayer != null) {
                mediaPlayer.setVolume(newVal.doubleValue() / 100.0);
            }
        });

        // 状态标签
        statusLabel = new Label("准备就绪");
        statusLabel.setStyle("-fx-text-fill: #2E8B57; -fx-font-weight: bold;");
    }

    private VBox createLayout() {
        VBox root = new VBox(15);
        root.setPadding(new Insets(15));
        root.setStyle("-fx-background-color: #2F4F4F;");

        // 标题
        Label titleLabel = new Label("服务端视频流测试播放器");
        titleLabel.setStyle("-fx-text-fill: white; -fx-font-size: 20px; -fx-font-weight: bold;");

        // 输入区域
        GridPane inputGrid = new GridPane();
        inputGrid.setHgap(10);
        inputGrid.setVgap(10);
        inputGrid.setPadding(new Insets(10));
        inputGrid.setStyle("-fx-background-color: #556B2F; -fx-background-radius: 5;");
        
        inputGrid.add(new Label("服务器:"), 0, 0);
        inputGrid.add(serverUrlField, 1, 0);
        inputGrid.add(new Label("项目:"), 0, 1);
        inputGrid.add(projectField, 1, 1);
        inputGrid.add(new Label("视频:"), 0, 2);
        inputGrid.add(videoNameField, 1, 2);
        
        serverUrlField.setPrefWidth(300);
        projectField.setPrefWidth(200);
        videoNameField.setPrefWidth(200);

        // 控制按钮区域
        HBox controlBox = new HBox(10);
        controlBox.setAlignment(Pos.CENTER);
        controlBox.getChildren().addAll(playButton, pauseButton, stopButton);
        
        // 音量控制
        HBox volumeBox = new HBox(10);
        volumeBox.setAlignment(Pos.CENTER_LEFT);
        volumeBox.getChildren().addAll(new Label("音量:"), volumeSlider);

        // 播放速率控制
        HBox rateBox = new HBox(10);
        rateBox.setAlignment(Pos.CENTER_LEFT);
        ComboBox<String> rateCombo = new ComboBox<>();
        rateCombo.getItems().addAll("0.5x", "1.0x", "1.5x", "2.0x");
        rateCombo.setValue("1.0x");
        rateCombo.setOnAction(e -> {
            String selected = rateCombo.getValue();
            double rate = Double.parseDouble(selected.replace("x", ""));
            playbackRate.set(rate);
            if (mediaPlayer != null) {
                mediaPlayer.setRate(rate);
            }
        });
        rateBox.getChildren().addAll(new Label("播放速度:"), rateCombo);

        // 状态区域
        HBox statusBox = new HBox(10);
        statusBox.setAlignment(Pos.CENTER);
        statusBox.getChildren().addAll(statusLabel, progressBar);

        // 组装所有组件
        root.getChildren().addAll(
            titleLabel,
            inputGrid,
            controlBox,
            new Separator(),
            mediaView,
            new Label("播放进度:"),
            seekSlider,
            new Separator(),
            volumeBox,
            rateBox,
            statusBox
        );

        return root;
    }

    private void playVideo() {
        try {
            String serverUrl = serverUrlField.getText().trim();
            String project = projectField.getText().trim();
            String videoName = videoNameField.getText().trim();
            
            if (project.isEmpty() || videoName.isEmpty()) {
                showError("请填写项目名称和视频名称");
                return;
            }

            // 编码URL参数
            String encodedProject = URLEncoder.encode(project, StandardCharsets.UTF_8.toString());
            String encodedVideoName = URLEncoder.encode(videoName, StandardCharsets.UTF_8.toString());
            
            String videoUrl = String.format("%s/api/videos/%s/%s", 
                serverUrl, encodedProject, encodedVideoName);
            
            updateStatus("正在连接: " + videoUrl);
            
            // 清理之前的播放器
            if (mediaPlayer != null) {
                mediaPlayer.dispose();
            }

            // 创建新的媒体播放器
            Media media = new Media(videoUrl);
            mediaPlayer = new MediaPlayer(media);
            mediaView.setMediaPlayer(mediaPlayer);
            
            // 设置播放速率
            mediaPlayer.setRate(playbackRate.get());
            mediaPlayer.setVolume(volumeSlider.getValue() / 100.0);

            // 设置事件监听器
            setupMediaListeners();

            // 开始播放
            mediaPlayer.play();
            updateStatus("正在播放: " + project + "/" + videoName);
            
            // 更新按钮状态
            playButton.setDisable(true);
            pauseButton.setDisable(false);
            stopButton.setDisable(false);

        } catch (UnsupportedEncodingException e) {
            showError("URL编码错误: " + e.getMessage());
        } catch (Exception e) {
            showError("播放错误: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private void setupMediaListeners() {
        mediaPlayer.setOnReady(() -> {
            updateStatus("媒体已加载完成");
            progressBar.setProgress(0);
        });

        mediaPlayer.setOnPlaying(() -> {
            updateStatus("播放中...");
        });

        mediaPlayer.setOnPaused(() -> {
            updateStatus("已暂停");
        });

        mediaPlayer.setOnStopped(() -> {
            updateStatus("已停止");
            resetControls();
        });

        mediaPlayer.setOnEndOfMedia(() -> {
            updateStatus("播放完成");
            resetControls();
            progressBar.setProgress(1.0);
        });

        mediaPlayer.setOnError(() -> {
            String errorMessage = mediaPlayer.getError() != null ? 
                mediaPlayer.getError().getMessage() : "未知错误";
            showError("媒体错误: " + errorMessage);
            resetControls();
        });

        // 更新进度条
        mediaPlayer.currentTimeProperty().addListener((obs, oldTime, newTime) -> {
            if (mediaPlayer.getTotalDuration().greaterThan(Duration.ZERO)) {
                double progress = newTime.toMillis() / mediaPlayer.getTotalDuration().toMillis();
                progressBar.setProgress(progress);
                seekSlider.setValue(progress * 100);
            }
        });
    }

    private void pauseVideo() {
        if (mediaPlayer != null) {
            mediaPlayer.pause();
            pauseButton.setDisable(true);
            playButton.setDisable(false);
        }
    }

    private void stopVideo() {
        if (mediaPlayer != null) {
            mediaPlayer.stop();
            resetControls();
        }
    }

    private void resetControls() {
        playButton.setDisable(false);
        pauseButton.setDisable(true);
        stopButton.setDisable(true);
        progressBar.setProgress(0);
        seekSlider.setValue(0);
    }

    private void updateStatus(String message) {
        Platform.runLater(() -> {
            statusLabel.setText(message);
            statusLabel.setStyle("-fx-text-fill: #2E8B57; -fx-font-weight: bold;");
        });
    }

    private void showError(String message) {
        Platform.runLater(() -> {
            statusLabel.setText("错误: " + message);
            statusLabel.setStyle("-fx-text-fill: #FF4500; -fx-font-weight: bold;");
        });
    }

    private void cleanup() {
        if (mediaPlayer != null) {
            mediaPlayer.dispose();
        }
    }

    public static void main(String[] args) {
        launch(args);
    }
}