package com.hi.music.player.helper;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.media3.common.MediaItem;
import androidx.palette.graphics.Palette;

import com.hi.music.player.MusicApplication;
import com.hi.music.player.R;
import com.hi.music.player.api.onImageColorListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.ResponseBody;

public class CommonUtils {

    private static String TAG = "----MUSIC---------";

    private static String TAG_ERROR = "----MUSIC---------ERROR--";

    public static void LogMsg(String msg) {
        Log.d(TAG, msg);
    }

    public static void LogErrorMsg(String msg) {
        Log.e(TAG_ERROR, msg);
    }

    public static JSONObject toJsonObject(ResponseBody body) {
        try {
            String string = body.string();
            return new JSONObject(string);
        } catch (IOException | JSONException exception) {
            return null;
        }
    }


    public static int dpToPx(int dp) {
        return Math.round(dp * (MusicApplication.myApplication.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
    }

    public static int pxToDp(int px) {
        return Math.round(px / (MusicApplication.myApplication.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
    }

    // 获取导航栏高度的方法
    public int getNavigationBarHeight(Context context) {
        int navigationBarHeight = 0;
        int resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
        if (resourceId > 0) {
            navigationBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        }
        return navigationBarHeight;
    }

    public static int getStatusBarHeight(Context context) {
        int statusBarHeight = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            statusBarHeight = context.getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight;
    }


    //time 3:45
    public static long convertToMilliseconds(String time) {
        String[] parts = time.split(":");
        int minutes = Integer.parseInt(parts[0]);
        int seconds = Integer.parseInt(parts[1]);

        return (minutes * 60 + seconds) * 1000; // 转换为毫秒
    }


    public static String convertMillisToTime(long millis) {
        long seconds = (millis / 1000) % 60;
        long minutes = (millis / (1000 * 60)) % 60;
        return String.format("%d:%02d", minutes, seconds); // 格式化为 mm:ss
    }

    public static int getMyColor(int resId) {
        return MusicApplication.myApplication.getColor(resId);
    }


    // 使用 Palette 提取深色主色调
    public static void getDominantDarkColor1(Drawable imDraw, onImageColorListener listener) {
        // 异步生成 Palette
        BitmapDrawable drawable = (BitmapDrawable) imDraw;
        if (drawable != null) {
            Bitmap bitmap = drawable.getBitmap();
            Palette.from(bitmap)
                    .generate(new Palette.PaletteAsyncListener() {
                        @Override
                        public void onGenerated(Palette palette) {
                            // 首先尝试获取深色活力色
                            Palette.Swatch darkVibrantSwatch = palette.getDarkVibrantSwatch();

                            // 如果没有深色活力色，尝试获取深色柔和色
                            if (darkVibrantSwatch == null) {
                                darkVibrantSwatch = palette.getDarkMutedSwatch();
                            }

                            // 如果存在深色样本，则获取其 RGB 颜色值
                            if (darkVibrantSwatch != null) {
                                int dominantDarkColor = darkVibrantSwatch.getRgb();
                                listener.onImageColor(dominantDarkColor);
                                String dominantColorHex = String.format("#%06X", (0xFFFFFF & dominantDarkColor));
                                Log.d("Dominant Dark Color", "主色调: " + dominantColorHex);  // 打印主色调
                            } else {
                                Log.d("Dominant Dark Color", "未找到深色主色调");
                                listener.onImageColor(-1);
                            }
                        }
                    });
        } else {
            listener.onImageColor(-1);
        }

    }

    // 调整颜色的亮度，factor > 1 表示变亮，factor < 1 表示变暗
    public static int adjustBrightness(int color, float factor) {
        // 将 RGB 颜色转换为 HSV
        float[] hsv = new float[3];
        Color.colorToHSV(color, hsv);

        // 调整亮度（V 值）
        hsv[2] = Math.min(1.0f, hsv[2] * factor);  // 亮度值最多是 1.0

        // 返回调整后的颜色（HSV 转回 RGB）
        return Color.HSVToColor(hsv);
    }


    public static Drawable getNewDrawable(int color, float RadiusTopLeft, float RadiusTopRight, float RadiusBottomRight, float RadiusBottomLeft) {
        // 创建 GradientDrawable
        GradientDrawable drawable = new GradientDrawable();

        // 设置形状为矩形
        drawable.setShape(GradientDrawable.RECTANGLE);

        // 设置背景颜色
        drawable.setColor(color);

        // 设置顶部圆角 (top-left and top-right)
        float[] radii = new float[]{
                RadiusTopLeft, RadiusTopLeft, // top-left radius
                RadiusTopRight, RadiusTopRight, // top-right radius
                RadiusBottomRight, RadiusBottomRight,   // bottom-right radius
                RadiusBottomLeft, RadiusBottomLeft    // bottom-left radius
        };
        drawable.setCornerRadii(radii);
        return drawable;
    }
    public static void extractColorsFromImage(Drawable drawable, View view) {
        Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();

        Palette.from(bitmap).generate(palette -> {
            if (palette != null) {
                // 获取主色
                int vibrantColor = palette.getVibrantColor(0);
                int mutedColor = palette.getMutedColor(0);

                // 创建左右渐变色
                createGradientBackground(vibrantColor, mutedColor,view);
            }
        });
    }

    private static void createGradientBackground(int leftColor, int rightColor, View view) {
         GradientDrawable gradientDrawable = new android.graphics.drawable.GradientDrawable(
                android.graphics.drawable.GradientDrawable.Orientation.LEFT_RIGHT,
                new int[]{leftColor, rightColor}

        );




        view.setBackground(gradientDrawable);

    }

    /**
     * 当前媒体项是否有有效的播放地址
     * @param mediaItem
     * @return
     */
    public static boolean hasValidUri(MediaItem mediaItem) {
        MediaItem.LocalConfiguration localConfiguration = mediaItem.localConfiguration;
        if(localConfiguration != null){
            if(CommonUtils.isUriFormat(localConfiguration.uri)){
                return true;
            }
        }
        return false;
    }

    private static boolean isUriFormat(Uri parsedUri) {
        // 3. 检查 URI 是否具有正确的格式
        try {
            if (parsedUri.getScheme() == null) {
                return false;
            }
        } catch (Exception e) {
            LogMsg(  "URI parsing failed: " + e.getMessage());
            return false;
        }
        return true;
    }
}
