package com.example.patrice.http01;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

//https://inducesmile.com/android/store-captured-image-in-sd-card-using-android-camera-application/

public class cam_capture04 extends Activity
{
    int REQUEST_TAKE_PHOTO = 1;
    String mCurrentPhotoPath;

    Button btnTakePhoto, btnUpload;
    TextView messageText;
    ImageView imgView;

    static String strSDCardPathName = Environment.getExternalStorageDirectory() + "/temp_picture" + "/";
    //    static String strURLUpload = "http://www.thaicreate.com/android/uploadFile.php";
    static String strURLUpload = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/upload_cam_capture01.php";

    String path_capture = "";

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.cam_capture02_layout);

        imgView = (ImageView) findViewById(R.id.imgView);
        messageText = (TextView) findViewById(R.id.messageText);
        btnTakePhoto = (Button) findViewById(R.id.btnTakePhoto);
        btnUpload = (Button) findViewById(R.id.btnUpload);

        btnTakePhoto.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                Intent photoCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(photoCaptureIntent, REQUEST_TAKE_PHOTO);
            }
        });

        btnUpload.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                //uploadFiletoServer(mCurrentPhotoPath, strURLUpload);
                new UploadFileAsync().execute(mCurrentPhotoPath, strURLUpload);
            }
        });

    }

    /*
    private File createImageFile() throws IOException
    {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        imageFileName = "tartuffe";
        File storageDir = new File(strSDCardPathName);
        File image = File.createTempFile(imageFileName, ".jpg", storageDir );
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }
    */

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        /*if (resultCode == RESULT_OK)
        {
            Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath);
            imgView.setImageBitmap(bitmap);
        }*/

        super.onActivityResult(requestCode, resultCode, data);

        if(this.REQUEST_TAKE_PHOTO == requestCode && resultCode == RESULT_OK)
        {
            Bitmap bitmap = (Bitmap)data.getExtras().get("data");
            String partFilename = currentDateFormat();
            storeCameraPhotoInSDCard(bitmap, partFilename);

            String storeFilename = "photo_" + partFilename + ".jpg";
            Bitmap mBitmap = getImageFileFromSDCard(storeFilename);
            imgView.setImageBitmap(mBitmap);

            path_capture = Environment.getExternalStorageDirectory() + "/" + storeFilename;

        }
    }

    private String currentDateFormat()
    {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        String  currentTimeStamp = dateFormat.format(new Date());
        return currentTimeStamp;
    }

    private void storeCameraPhotoInSDCard(Bitmap bitmap, String currentDate)
    {
        File outputFile = new File(Environment.getExternalStorageDirectory(), "photo_" + currentDate + ".jpg");
        try
        {
            FileOutputStream fileOutputStream = new FileOutputStream(outputFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();

        }

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

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

    private Bitmap getImageFileFromSDCard(String filename)
    {
        Bitmap bitmap = null;
        File imageFile = new File(Environment.getExternalStorageDirectory() + filename);

        try
        {
            FileInputStream fis = new FileInputStream(imageFile);
            bitmap = BitmapFactory.decodeStream(fis);
        }

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

        return bitmap;
    }

    private class UploadFileAsync extends AsyncTask<String, Void, String>
    {
        @Override
        protected String doInBackground(String... params)
        {
            try
            {
                path_capture = Environment.getExternalStorageDirectory() + "/" + "log.file"; // pour le debug

                String sourceFileUri = path_capture;
                String upLoadServerUri = "http://analog-design.net/WORKAREA/WEBSITE/Codebar/upload_asyntask01.php?"; // rajouer ? en fin de chaine

                int serverResponseCode = 0;
                HttpURLConnection conn = null;
                DataOutputStream dos = null;
                String lineEnd = "\r\n";
                String twoHyphens = "--";
                String boundary = "*****";
                int bytesRead, bytesAvailable, bufferSize;
                byte[] buffer;
                int maxBufferSize = 1 * 1024 * 1024;
                File sourceFile = new File(sourceFileUri);

                if (sourceFile.isFile())
                {

                    try
                    {

                        FileInputStream fileInputStream = new FileInputStream(sourceFile);
                        URL url = new URL(upLoadServerUri);
                        conn = (HttpURLConnection) url.openConnection();

                        conn.setConnectTimeout(15000);
                        conn.setReadTimeout(15000);

                        conn.setDoInput(true); // Allow Inputs
                        conn.setDoOutput(true); // Allow Outputs
                        conn.setUseCaches(false); // Don't use a Cached Copy
                        conn.setRequestMethod("POST");
                        conn.setRequestProperty("Connection", "Keep-Alive");
                        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                        conn.setRequestProperty("bill", sourceFileUri);

                        dos = new DataOutputStream(conn.getOutputStream());

                        dos.writeBytes(twoHyphens + boundary + lineEnd);
                        dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\"" + sourceFileUri + "\"" + lineEnd);

                        dos.writeBytes(lineEnd);

                        // create a buffer of maximum size
                        bytesAvailable = fileInputStream.available();

                        bufferSize = Math.min(bytesAvailable, maxBufferSize);
                        buffer = new byte[bufferSize];

                        // read file and write it into form...
                        bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                        while (bytesRead > 0)
                        {
                            dos.write(buffer, 0, bufferSize);
                            bytesAvailable = fileInputStream.available();
                            bufferSize = Math.min(bytesAvailable, maxBufferSize);
                            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                        }

                        dos.writeBytes(lineEnd);
                        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                        // Responses from the server (code and message)
                        serverResponseCode = conn.getResponseCode();
                        String serverResponseMessage = conn.getResponseMessage();

                        if (serverResponseCode == 200)
                        {
                            String result = "OK";
                            //messageText.setText("Reçu");
                        }

                        // close the streams
                        fileInputStream.close();
                        dos.flush();
                        dos.close();

                    }

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

                }

            }

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

            return "Executed";
        }

        @Override
        protected void onPostExecute(String result)
        {
        }

        @Override
        protected void onPreExecute()
        {
        }

        @Override
        protected void onProgressUpdate(Void... values)
        {
        }
    }

}
