package com.img.rabbit.utils;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.widget.Toast;

public class Bitmap2SVG
{
    public static boolean convert(Context context, File output, Bitmap input){
        Bitmap2SVG svg;
        try
        {
            svg = new Bitmap2SVG( new PrintWriter( new BufferedWriter( new FileWriter( output ) ) ), true );
        } catch (IOException e)
        {
            return false;
        }

        svg.printSVGHeader( input.getWidth(), input.getHeight() );
        svg.printSVGBody( input );
        svg.printSVGFooter();

        saveToGallery(context, output, "displayName.svg");

        return true;
    }

    private final boolean trc_del;
    private final PrintWriter pw;
    private int w, h;

    private Bitmap2SVG( PrintWriter pw, boolean trc_delete )
    {
        this.pw = pw;
        trc_del = trc_delete;
    }
    private void printSVGHeader( int width, int height )
    {
        pw.println( "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" );

        pw.print( "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" width=\"" );
        pw.print( width );
        pw.print( "\" height=\"" );
        pw.print( height );
        pw.println( "\">" );
    }
    private void printSVGFooter()
    {
        pw.println( "</svg>" );
        pw.close();
    }
    private void printSVGBody( Bitmap bmp )
    {
        int x, y, c, a;
        w = bmp.getWidth();
        h = bmp.getHeight();
        for ( y = 0 ; y < h ; ++y )
        {
            for ( x = 0 ; x < w ;++x )
            {
                c = bmp.getPixel( x, y );
                a = Color.alpha( c );
                if ( trc_del && a == 0 ){ continue; }
                printDot( x, y, rgb( c ), a );
            }
        }
    }
    private void printDot( int x, int y, String rgb, int a )
    {
        pw.print( "<rect width=\"1\" height=\"1\" x=\"" );
        pw.print( x );
        pw.print( "\" y=\"" );
        pw.print( y );
        pw.print( "\" " );
        pw.print( "style=\"fill:#" );
        pw.print( rgb );
        if ( a < 255 )
        {
            pw.print( ";fill-opacity:" );
            pw.print( a / 255.0 );
        }
        pw.println( ";\" />" );
    }
    private static String rgb( int c )
    {
        return String.format( "%02x%02x%02x", Color.red( c ), Color.green( c ), Color.blue( c ) );
    }

    public static void saveToGallery(Context context, File svgFile, String displayName) {
        ContentValues values = new ContentValues();
        // 关键点：显式指定 MIME 类型为 SVG
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/svg+xml");
        values.put(MediaStore.Images.Media.DISPLAY_NAME, displayName + ".svg");
        values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES);

        ContentResolver resolver = context.getContentResolver();
        Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        if (uri != null) {
            try (OutputStream os = resolver.openOutputStream(uri);
                 FileInputStream fis = new FileInputStream(svgFile)) {
                byte[] buffer = new byte[1024];
                int len;
                while ((len = fis.read(buffer)) != -1) {
                    assert os != null;
                    os.write(buffer, 0, len);
                }
                // 此时文件已带上正确的 MIME 类型存入相册
                Toast.makeText(context, "SVG已保存", Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                //noinspection CallToPrintStackTrace
                e.printStackTrace();
            }
        }
    }
}
