package com.example.Fruits;


import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.FileProvider;

import com.transfer.Ingredient;
import com.transfer.ToIngredient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;


public class PictureSearchActivity extends AppCompatActivity {

    Bitmap bitmap;
    final int TAKE_PHOTO=1;
    Button btn_1;
    ImageView iv_photo;
    Uri imageUri;
    TextView t1;
    String a="111";
    @Override
    protected void onCreate(Bundle savedInstanceState){

        // Android在4.0之前的版本支持在主线程中访问网络，但是在4.0以后对这部分程序进行了优化，也就是说访问网络的代码不能写在主线程中了。
        //主线程中进行网络请求异常, Android4.0 版本开始后就强制程序不能在主线程中访问网络, 要把访问网络放在独立的子线程中.
        //在 Activity 的 onCreate() 方法中添加, 忽略这些强制策略.
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);


        super.onCreate(savedInstanceState);
        setContentView(R.layout.picture_search_activity);

        btn_1=findViewById(R.id.btn_takephoto);
        iv_photo=findViewById(R.id.img_photo);
        t1=findViewById(R.id.textView11);


        btn_1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File output=new File(getExternalCacheDir(),"output_image.jpg");
                try {
                    if (output.exists()){
                        output.delete();
                    }
                    output.createNewFile();
                }catch (IOException e){
                    e.printStackTrace();
                }
                if (Build.VERSION.SDK_INT>=24){
                    //图片的保存路径
                    imageUri= FileProvider.getUriForFile(PictureSearchActivity.this,"com.example.takephoto.fileprovider",output);
                }
                else { imageUri=Uri.fromFile(output);
                }
                //跳转界面到系统自带的拍照界面
                Intent intent=new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT,imageUri);
                startActivityForResult(intent,TAKE_PHOTO);
            }
        });


    }

    public void saveImageToGallery(Context context, Bitmap bitmap) {
        //检查有没有存储权限
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "请至权限中心打开应用权限", Toast.LENGTH_SHORT).show();
        } else {
            // 新建目录appDir，并把图片存到其下
            File appDir = new File(context.getExternalFilesDir(null).getPath() + "BarcodeBitmap");
            if (!appDir.exists()) {
                appDir.mkdir();
            }

            Random random = new Random();
            //生成随机数的个数
            int random1 = 0;
            for (int i = 0; i < 6; i++) {
                random1 = random.nextInt(1000000);
            }

            String fileName = String.format("%s.jpg", String.valueOf(random1));
            a = context.getExternalFilesDir(null).getPath() + "BarcodeBitmap/" + fileName;

            File file = new File(appDir, fileName);
            try {
                FileOutputStream fos = new FileOutputStream(file);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

//            // 把file里面的图片插入到系统相册中
//            try {
//                MediaStore.Images.Media.insertImage(context.getContentResolver(),
//                        file.getAbsolutePath(), fileName, null);
//            } catch (FileNotFoundException e) {
//                e.printStackTrace();
//            }
//
//            Toast.makeText(this, fileName, Toast.LENGTH_LONG);
//
//            // 通知相册更新
//            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
        }
    }

    @Override
    public  void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case TAKE_PHOTO:
                if (resultCode==RESULT_OK){
                    // 使用try让程序运行在内报错
                    try {
                        //将图片保存
                        bitmap= BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        iv_photo.setImageBitmap(bitmap);
                        saveImageToGallery(PictureSearchActivity.this,bitmap);

                        Ingredient qw=new Ingredient(a);
                        String str=qw.ingredient();
                        ToIngredient s= new ToIngredient(str);

                        t1.setText("识别结果："+"\n"+s.train());//"图片保存位置:"+"\n"+a+"\n"+

                    }catch (FileNotFoundException e){
                        e.printStackTrace();
                    }
                }
                break;
            default:break;
        }

    }



}