package com.usai.redant.CommonEditor;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;


import com.usai.redant.redantmobile.R;

import java.io.File;
import java.util.UUID;

public class ImageUploadActivity extends AppCompatActivity {

    private ImageView imageView;
    private ImageButton albumBtn;
    private ImageButton takeBtn;
    private ImageButton uploadBtn;
    private String img_path;
    private Bitmap bitmap;

    private Context mCtx = this;

    private static int ALBUM_REQUEST_CODE = 1;
    private static int CAMERA_REQUEST_CODE = 2;

    private int group;
    private int child;
    private int btn_tag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_upload);

        imageView = (ImageView) findViewById(R.id.img_view);
        albumBtn = (ImageButton) findViewById(R.id.photo_library_btn);
        takeBtn = (ImageButton) findViewById(R.id.tack_photo_btn);
        uploadBtn = (ImageButton) findViewById(R.id.photo_upload_btn);

        Intent intent = getIntent();
        group = intent.getIntExtra("group",0);
        child = intent.getIntExtra("child",0);
        btn_tag = intent.getIntExtra("btn",0);


        if (savedInstanceState != null) {
            img_path = savedInstanceState.getString("img_path");
            if (img_path != null && !img_path.isEmpty()) {
                bitmap = BitmapFactory.decodeFile(img_path);
                imageView.setImageBitmap(bitmap);
            }
        }

        albumBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intent, ALBUM_REQUEST_CODE);
            }
        });

        takeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                img_path = startCamera((ImageUploadActivity)mCtx,CAMERA_REQUEST_CODE);
            }
        });

        uploadBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                if (img_path != null && !img_path.isEmpty()) {
                    // upload


                    UUID uuid = UUID.randomUUID();
                    String img_path = Utils.cacheTmpImage(bitmap);

                    // upload success
                    Intent intent = new Intent();
                    intent.putExtra("url_down",uuid.toString());
                    intent.putExtra("url_up",uuid.toString());
                    intent.putExtra("path",img_path);
                    intent.putExtra("group",group);
                    intent.putExtra("child",child);
                    intent.putExtra("btn",btn_tag);
                    setResult(RESULT_OK,intent);
                    finish();
                }

            }
        });
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        outState.putString("img_path",img_path);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == ALBUM_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                try {
                    Uri uri = data.getData();
                    final String absolutePath= getAbsolutePath(this, uri);
                    img_path = absolutePath;
                    if (img_path != null) {
                        bitmap = BitmapFactory.decodeFile(img_path);
                        imageView.setImageBitmap(bitmap);
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                if (img_path != null) {
                    bitmap = BitmapFactory.decodeFile(img_path);
                    imageView.setImageBitmap(bitmap);
                }

            }
        }

    }

    public String getAbsolutePath(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri,
                    new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    public static String startCamera(Activity activity, int requestCode) {
        // 指定相机拍摄照片保存地址
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent();
            // 指定开启系统相机的Action
            intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            File outDir = Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
            if (!outDir.exists()) {
                outDir.mkdirs();
            }
            File outFile = new File(outDir, System.currentTimeMillis() + ".jpg");
            // 把文件地址转换成Uri格式
            Uri uri = Uri.fromFile(outFile);
            // 设置系统相机拍摄照片完成后图片文件的存放地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            // 此值在最低质量最小文件尺寸时是0，在最高质量最大文件尺寸时是１
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
            activity.startActivityForResult(intent, requestCode);
            return outFile.getAbsolutePath();
        } else {
            Toast.makeText(activity, "请确认已经插入SD卡",
                    Toast.LENGTH_LONG).show();
            return null;
        }
    }
}
