package com.ecom.park_jy;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraManager;
import android.media.ExifInterface;
import android.opengl.GLSurfaceView;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.security.Policy;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

//拍照相機
public class park_cam extends AppCompatActivity implements SurfaceHolder.Callback, Camera.AutoFocusCallback, CompoundButton.OnCheckedChangeListener {
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private Camera.Parameters parameters;
    Button button;
    ToggleButton tg;
    private boolean isFlashon = false;
    int x2 = 0;
    OrientationEventListener msor;
    int ex;
    Calendar calendar;
    Bundle bundle = new Bundle();
    String bill;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_park_cam);

        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(this);
        button = (Button) findViewById(R.id.button15);
        tg = (ToggleButton) findViewById(R.id.toggleButton);
        msor = new OrientationEventListener(this) {  //獲取螢幕方向
            @Override
            public void onOrientationChanged(int orientation) {
                if (orientation >= 45 && orientation < 135) {
                    ex = ExifInterface.ORIENTATION_ROTATE_180;
                } else if (orientation >= 135 && orientation < 225) {
                    ex = ExifInterface.ORIENTATION_ROTATE_270;
                } else if (orientation >= 225 && orientation < 315) {
                    ex = ExifInterface.ORIENTATION_NORMAL;
                } else {
                    ex = ExifInterface.ORIENTATION_ROTATE_90;
                }
            }
        };
        if (msor.canDetectOrientation()) {
            msor.enable();
        }
        //imv = (ImageView)findViewById(R.id.image);
        getSupportActionBar().hide(); //隱藏標題
        getLastNonConfigurationInstance();
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN); //隱藏狀態列
        bundle = this.getIntent().getExtras();
        bill = bundle.getString("billNumber");
        x2 = bundle.getInt("photoCount");

        tg.setOnCheckedChangeListener(this);
    }

    public void bt_action(View view) {
        try {
            camera.autoFocus(this); //自動對焦
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (isFlashon) {
            camera.takePicture(null, null, jpeg); //拍照
            final ProgressDialog mProcessDlg = ProgressDialog.show(park_cam.this, "存檔中...", "存檔中，請稍候...", true);
            isFlashon = false;
        }
        Toast.makeText(park_cam.this, "拍照完成", Toast.LENGTH_SHORT).show();
        //Toast.makeText(park_cam.this,"上傳成功",Toast.LENGTH_SHORT).show();
        //camera.startPreview();
    }

    @Override
    public void onAutoFocus(boolean b, Camera camera) {
        if (b) {
            camera.cancelAutoFocus();
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        camera = Camera.open(0);
        try {
            camera.setPreviewDisplay(surfaceHolder);
            camera.setDisplayOrientation(90);
        } catch (IOException e) {
            camera.release();
            camera = null;
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
        parameters = camera.getParameters(); //取得相機參數
        //System.out.println(fac);
        List<Camera.Size> prevsizes = parameters.getSupportedPreviewSizes();//取得預覽尺寸
        Camera.Size opsize = prevsizes.get(0);
        parameters.setPictureSize(opsize.width, opsize.height); //輸出照片像素
        parameters.setPictureFormat(PixelFormat.JPEG);
        camera.setParameters(parameters);
        camera.startPreview();
        isFlashon = true;
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE); //重複自動對焦
        try {
            camera.autoFocus(this); //自動對焦
            setDisplayro(this, Camera.CameraInfo.CAMERA_FACING_BACK, camera);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        camera.stopPreview();
        camera.release();
        camera = null;
    }

    Camera.PictureCallback jpeg = new Camera.PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            if (data != null) {
                SimpleDateFormat simple = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                Bitmap picture = BitmapFactory.decodeByteArray(data, 0, data.length);
                picture = rbitmap(picture);
                calendar = Calendar.getInstance();
                String path = Environment.getExternalStorageDirectory() + "/park_jy/photo/" + calendar.get(Calendar.YEAR);
                if (((calendar.get(Calendar.MONTH)) + 1) < 10) {
                    path += "0";
                }
                path += calendar.get(Calendar.MONTH) + 1;
                if (calendar.get(Calendar.DATE) < 10) {
                    path += "0";
                }
                path += calendar.get(Calendar.DAY_OF_MONTH);

                File dir = new File(path);
                FileOutputStream fo = null;
                File[] lis = dir.listFiles();
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                /*if(lis.length > 0){
                    x2 = lis.length;
                }else if(x2 == lis.length && lis.length != 0){
                    x2 = lis.length + 1;
                }else if(lis.length == 0){
                    x2 = 0;
                }*/

                RequestParams params = new RequestParams();
                try {
                    fo = new FileOutputStream(path + "/" + bill + x2 + ".jpg");
                    picture.compress(Bitmap.CompressFormat.JPEG, 75, fo);
                    try {
                        fo.flush();
                        fo.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    params.put("ticket_id", bill);
                    params.put("file", new File(path + "/" + bill + x2 + ".jpg"));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                Bitmap bmpcopy = BitmapFactory.decodeFile(path + "/" + bill + x2 + ".jpg").copy(Bitmap.Config.ARGB_8888, true);
                Canvas canvas = new Canvas(bmpcopy);
                Paint p = new Paint();
                p.setColor(Color.RED);
                p.setTextSize(100);
                canvas.drawBitmap(bmpcopy, 0, 0, p);
                canvas.drawText(simple.format(new Date()), bmpcopy.getWidth() / 3 + 180, bmpcopy.getHeight(), p);
                canvas.save(Canvas.ALL_SAVE_FLAG);
                canvas.restore();

                try {
                    fo = new FileOutputStream(path + "/" + bill + x2 + ".jpg");
                    bmpcopy.compress(Bitmap.CompressFormat.JPEG, 75, fo);
                    try {
                        fo.flush();
                        fo.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    params.put("ticket_id", bill);
                    params.put("file", new File(path + "/" + bill + x2 + ".jpg"));
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }

                final String pathf = path;
                //AsyncHttpClient image = new AsyncHttpClient();
                /*image.post("http://125.227.205.151:1000/ap/v/detect", params, new AsyncHttpResponseHandler() {
                    @Override
                    public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
                        //Toast.makeText(park_cam.this,"上傳成功",Toast.LENGTH_SHORT).show();
                        File test = new File(pathf + "/test");
                        if(!test.exists()){
                           test.mkdirs();
                        }
                        try {
                            FileOutputStream out = new FileOutputStream(pathf +"/test/" +bill + x2 + ".jpg");
                            try {
                                out.write(bytes);
                                out.flush();
                                out.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

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

                    @Override
                    public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {

                    }
                });*/
                Intent intent = new Intent(park_cam.this, Start.class);
                bundle.putInt("x", x2);
                /*if(x2 == 0){
                    bundle.putInt("x",x2);
                }else{
                    bundle.putInt("x",x2-1);
                }*/
                intent.putExtras(bundle);
                setResult(RESULT_OK, intent);
                finish();
            }
        }
    };

    public Bitmap rbitmap(Bitmap picture) { //照片轉向
        Bitmap rb = null;
        Matrix matrix = new Matrix();
        if (ex == 6) {
            matrix.postRotate(90);
        } else if (ex == 1) {
            matrix.postRotate(0);
        } else if (ex == 3) {
            matrix.postRotate(180);
        } else if (ex == 8) {
            matrix.postRotate(270);
        }

        Bitmap scale = Bitmap.createScaledBitmap(picture, picture.getWidth(), picture.getHeight(), true);
        rb = Bitmap.createBitmap(scale, 0, 0, scale.getWidth(), scale.getHeight(), matrix, true);
        return rb;
    }

    private static int clamp(int x, int min, int max) {
        if (x > max) {
            return max;
        }
        if (x < min) {
            return min;
        }
        return x;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            Rect trF = new Rect((int) (x - 100), (int) (y - 100), (int) (x + 100), (int) (y + 100));
            final Rect trFt = new Rect(clamp((trF.left * 2000 / surfaceView.getWidth() - 900), -1000, 1000), clamp((trF.top * 2000 / surfaceView.getHeight() - 1000), -1000, 1000), clamp((trF.right * 2000 / surfaceView.getWidth() - 900), -1000, 1000), clamp((trF.bottom * 2000 / surfaceView.getHeight() - 1000), -1000, 1000));
            parameters = camera.getParameters();
            List<Camera.Area> focusL = new ArrayList<>();
            focusL.add(new Camera.Area(trFt, 1000));
            parameters.setFocusAreas(focusL);
            parameters.setMeteringAreas(focusL);
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_MACRO);
            try {
                camera.setParameters(parameters);
                camera.autoFocus(this);
                //Toast.makeText(park_cam.this,"Xl:"+Integer.toString(trFt.left)+",Yt:"+Integer.toString(trFt.top)+",Xr:"+Integer.toString(trFt.right)+"Yb:"+Integer.toString(trFt.bottom) +","+ Integer.toString(x2),Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return true;
    }


    public static void setDisplayro(Activity activity, int cId, Camera camera) { //相機預覽隨手機方向轉變
        Camera.CameraInfo info = new Camera.CameraInfo();
        Camera.getCameraInfo(cId, info);
        int or = activity.getWindowManager().getDefaultDisplay().getRotation();
        int deg = 0;
        switch (or) {
            case Surface.ROTATION_0:
                deg = 0;
                break;
            case Surface.ROTATION_90:
                deg = 90;
                break;
            case Surface.ROTATION_180:
                deg = 180;
                break;
            case Surface.ROTATION_270:
                deg = 270;
                break;
        }
        int result = (info.orientation - deg + 360) % 360;
        camera.setDisplayOrientation(result);
    }

    @Override //閃光燈開關
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (buttonView.isChecked()) {
            //tg.setTextOn("開啟");
            tg.setBackgroundResource(R.drawable.flash_on);
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_AUTO);
            camera.setParameters(parameters);
        } else {
            //tg.setTextOff("關閉");
            tg.setBackgroundResource(R.drawable.flash_off);
            parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
            camera.setParameters(parameters);
        }
    }
}
