package com.example.audiovisualrecord.ui.main;

import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
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.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.audiovisualrecord.FileUtil;
import com.example.audiovisualrecord.MagicFileChooser;
import com.example.audiovisualrecord.R;
import com.example.audiovisualrecord.base.BaseActivity;
import com.example.audiovisualrecord.ui.chooseitem.ChooseDeviceItemData;
import com.example.audiovisualrecord.utils.api.apidata.searchco.COResponse;
import com.example.audiovisualrecord.utils.api.apidata.searchtype.TYPEResponse;
import com.example.audiovisualrecord.utils.api.searchshift.SHIFTResponse;
import com.example.audiovisualrecord.utils.api.searchpz.PZResponse;
import com.example.audiovisualrecord.utils.api.searchdp.DPResponse;


import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class MainActivity extends BaseActivity implements MainContract.View, View.OnClickListener {


    private static final int REQUEST_CAPTURE_IMAGE = 100;
    private static final int REQUEST_VIDEO_CAPTURE = 200;
    private static final int PICK_IMAGE_FROM_GALLERY_REQUEST_CODE = 300;
    private static final int PICK_VIDEO_FROM_GALLERY_REQUEST_CODE = 400;
    private static final int PICK_FILE_REQUEST_CODE = 500;

    private Button btnCapturePicture, btnRecordVideo, btnGetImageFromGallery, btnGetVideoFromGallery, btnDeviceEdit, btnCentralCloud, btnChoseDevice, btnBasicInformation;
    private File photoFile;

    private String pathCompany = "";
    private String pathFactoryArea= "";
    private String pathFactoryClass= "";
    private String pathClass= "";
    private String pathShootType = "";
    private String uploadPath = "";

    //    Bundle bag;
    String token, imageFilePath;
    int countFile = 0;

    private TextView tvCompany, tvFactory, tvClass, tvUnit, tvShootType;
    private TextView textCompany, textFactory, textClass, textUnit, textShootType;
    private MainPresenter mPresenter;
    private MainData mMainData;
    private ChooseDeviceItemData mChooseDeviceItemData;
    private ArrayList<String> dialogString = new ArrayList<>();

    private List<String> filepath = new ArrayList<>();
    private List<String> filename = new ArrayList<>();

    String sidData ="";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        bag = getIntent().getExtras();
//        token = bag.getString("token");
        init();
        mPresenter = new MainPresenter(this);
        mMainData = new MainData();
        mChooseDeviceItemData = new ChooseDeviceItemData();
//        mPresenter.onGetSid();
    }

    @Override
    public void init() {
        btnCapturePicture = findViewById(R.id.btnCaptureImage);
        btnGetImageFromGallery = findViewById(R.id.btnGetImageFromGallery);
        btnGetVideoFromGallery = findViewById(R.id.btnGetVideoFromGallery);
        btnRecordVideo = findViewById(R.id.btnRecordVideo);
        btnCapturePicture.setOnClickListener(this);
        btnGetImageFromGallery.setOnClickListener(this);
        btnGetVideoFromGallery.setOnClickListener(this);
        btnRecordVideo.setOnClickListener(this);
        tvCompany = findViewById(R.id.tv_company);
        tvFactory = findViewById(R.id.tv_factory);
        tvUnit = findViewById(R.id.tv_unit);
        tvClass = findViewById(R.id.tv_class);
        tvShootType = findViewById(R.id.tv_shoottype);
        tvCompany.setOnClickListener(this);
        tvFactory.setOnClickListener(this);
        tvUnit.setOnClickListener(this);
        tvClass.setOnClickListener(this);
        tvShootType.setOnClickListener(this);
        textCompany = findViewById(R.id.text_company);
        textUnit = findViewById(R.id.text_unit);
        textShootType = findViewById(R.id.text_shoottype);
        textFactory = findViewById(R.id.text_factory);
        textClass = findViewById(R.id.text_class);

    }

    private void pickImageFromGallery() {

        //Create an Intent with action as ACTION_PICK
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        // Sets the type as image/*. This ensures only components of type image are selected
        intent.setType("image/*");

        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        //We pass an extra array with the accepted mime types. This will ensure only components with these MIME types as targeted.
        String[] mimeTypes = {"image/jpeg", "image/png"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        // Launching the Intent
        startActivityForResult(intent, PICK_IMAGE_FROM_GALLERY_REQUEST_CODE);
    }

    private void pickVideoFromGallery() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("video/*");
        intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
        String[] mimeTypes = {"video/mp4", "video/mov"};
        intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
        startActivityForResult(intent, PICK_VIDEO_FROM_GALLERY_REQUEST_CODE);

    }

    private void openCameraIntent() {
        Intent pictureIntent = new Intent(
                MediaStore.ACTION_IMAGE_CAPTURE);
        settingSystemCamera(pictureIntent);
        if (pictureIntent.resolveActivity(getPackageManager()) != null) {
            //Create a file to store the image
            photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File

            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this, "com.example.audiovisualrecord.provider", photoFile);
                pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        photoURI);
                startActivityForResult(pictureIntent,
                        REQUEST_CAPTURE_IMAGE);
            }
        }
    }

    private void openRecordVideoIntent() {
        Intent takeVideoIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        PackageManager packageManager = this.getPackageManager();
        List<ResolveInfo> listCam = packageManager.queryIntentActivities(takeVideoIntent, 0);
        takeVideoIntent.setPackage(listCam.get(0).activityInfo.packageName);
//        takeVideoIntent.putExtra(MediaStore.EXTRA_SIZE_LIMIT, 10996480L);  //限制影片大小
        if (takeVideoIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takeVideoIntent, REQUEST_VIDEO_CAPTURE);
        }
    }

    private File createImageFile() throws IOException {
        String timeStamp =
                new SimpleDateFormat("yyyyMMdd_HHmmss",
                        Locale.getDefault()).format(new Date());
        String imageFileName = "IMG_" + timeStamp + "_";
        File storageDir =
                getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        imageFilePath = image.getAbsolutePath();
        return image;
    }

    private void settingSystemCamera(Intent intent) {
        PackageManager packageManager = MainActivity.this.getPackageManager();
        List<ResolveInfo> listCam = packageManager.queryIntentActivities(intent, 0);
        intent.setPackage(listCam.get(0).activityInfo.packageName);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAPTURE_IMAGE && resultCode == RESULT_OK) {
            File imgFile = new File(imageFilePath);
            //照片的檔案
            if (imgFile.exists()) {
                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
                try {
                    FileOutputStream out = new FileOutputStream(imgFile);
                    myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
                    out.flush();
                    out.close();

                    MediaStore.Images.Media.insertImage(getContentResolver(), myBitmap, imgFile.getName(), "description");
                    sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()))));

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

        if (requestCode == REQUEST_VIDEO_CAPTURE && resultCode == RESULT_OK) {
            //影片的uri
            Uri videoUri = data.getData();
        }

        if (requestCode == PICK_IMAGE_FROM_GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {
            ArrayList<String> uriList = new ArrayList<String>();

            if (data.getClipData() != null) {
                for (int i = 0; i < data.getClipData().getItemCount(); i++) {
                    uriList.add(getPath(data.getClipData().getItemAt(i).getUri()));
//                    Log.e("gggg", "" + uriList.get(i));
                }
            } else if (Build.VERSION.SDK_INT >= 16 && data.getClipData() == null) {
                uriList.add(getPath(data.getData()));
            }
            //照片的uri
             mPresenter.onGetSid(uriList,getResourceString(R.string.on_upload_image));
        }

        if (requestCode == PICK_VIDEO_FROM_GALLERY_REQUEST_CODE && resultCode == RESULT_OK) {
            ArrayList<String> uriList = new ArrayList<String>();

            if (data.getClipData() != null) {
                Uri selectedVideo = data.getClipData().getItemAt(0).getUri();
                int count = data.getClipData().getItemCount();
                //count 選取檔案的數量
                for (int i = 0; i < count; i++) {
                    uriList.add(getPath(data.getClipData().getItemAt(i).getUri()));
                    filename.add(FileUtil.fileName(getPath(data.getClipData().getItemAt(i).getUri())));
//                    Log.e("gggg", "" + uriList.get(i));
//                    Log.e("dddd", "" + filename.get(i));
                }
                Log.e("aaa", count + "");

            } else if (Build.VERSION.SDK_INT >= 16 && data.getClipData() == null) {
                uriList.clear();

                String path = FileUtil.getFileAbsolutePath(this, data.getData());
                String name = FileUtil.fileName(path);
                uriList.add(path);
                mPresenter.segVideo(path, getResourceString(R.string.on_upload_vedio));
                // TODO here====================
                //影片的uri
            }


        }
        if (requestCode == PICK_FILE_REQUEST_CODE && resultCode == RESULT_OK) {
            Uri selectedFile = data.getData();
            String filePath = MagicFileChooser.getAbsolutePathFromUri(this, selectedFile);
//            Log.e("filePath", filePath + "");
//            Log.e("ggggg", "" + selectedFile);
            checkFileTypeAndOpen(filePath, selectedFile);
        }
    }

    //根據副檔名判斷用什麼應用程式開啟
    private void checkFileTypeAndOpen(String filePath, Uri selectedFile) {
        final Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        if (filePath.contains(".doc")) {
            intent.setDataAndType(selectedFile, "application/msword");
        } else if (filePath.contains(".ppt")) {
            intent.setDataAndType(selectedFile, "application/vnd.ms-powerpoint");
        } else if ((filePath.contains(".csv")) || (filePath.contains(".xls"))) {
            intent.setDataAndType(selectedFile, "application/vnd.ms-excel");
        } else if (filePath.contains(".pdf")) {
            intent.setDataAndType(selectedFile, "application/pdf");
        } else if (filePath.contains(".txt")) {
            intent.setDataAndType(selectedFile, "text/plain");
        } else {
            intent.setDataAndType(selectedFile, "application/*");
        }

        PackageManager pm = getPackageManager();
        List<ResolveInfo> list = pm.queryIntentActivities(intent, 0);
        if (list.size() > 0)
            startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnCaptureImage:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea,pathFactoryClass,pathClass,pathShootType);
                if ("".equals(uploadPath)){
                    showDialogCaveatMessage("請選擇路徑");
                }else {
                    openCameraIntent();
                }

                break;

            case R.id.btnGetImageFromGallery:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea,pathFactoryClass,pathClass,pathShootType);
                if ("".equals(uploadPath)){
                    showDialogCaveatMessage("請選擇路徑");
                }else {
                    pickImageFromGallery();
                }


                break;

            case R.id.btnGetVideoFromGallery:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea,pathFactoryClass,pathClass,pathShootType);
                if ("".equals(uploadPath)){
                    showDialogCaveatMessage("請選擇路徑");
                }else {
                    pickVideoFromGallery();
                }

                break;

            case R.id.btnRecordVideo:
                uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea,pathFactoryClass,pathClass,pathShootType);
                if ("".equals(uploadPath)){
                    showDialogCaveatMessage("請選擇路徑");
                }else {
                    openRecordVideoIntent();
                }

                break;

            case R.id.tv_company:
                mPresenter.onGetComData();
                break;

            case R.id.tv_factory:
                mPresenter.onGetPZData();
                break;

            case R.id.tv_unit:
                if (mChooseDeviceItemData.getFactoryAreaId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_maintenance_plant_error));
                }
                if (mChooseDeviceItemData.getCompanyId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_company_error));
                }
                mPresenter.onGetDPData(mChooseDeviceItemData.getCompanyId(), mChooseDeviceItemData.getFactoryAreaId());
                break;

            case R.id.tv_class:
                if (mChooseDeviceItemData.getCompanyId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_company_error));
                }
                if (mChooseDeviceItemData.getProductionPlantId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_production_plant_error));
                }
                mPresenter.onGetSHIFTData(mChooseDeviceItemData.getCompanyId(), mChooseDeviceItemData.getProductionPlantId());
                break;

            case R.id.tv_shoottype:
                if (mChooseDeviceItemData.getCompanyId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_company_error));
                }
                if (mChooseDeviceItemData.getProductionPlantId().equals("")) {
                    showDialogCaveatMessage(getResourceString(R.string.add_device_no_production_plant_error));
                }
                mPresenter.onGetTYPEData(mChooseDeviceItemData.getCompanyId(), mChooseDeviceItemData.getProductionPlantId()
                );

                break;
        }
    }

    @Override
    public void setCOData(List<COResponse> adapterData) {
        dialogString.clear();
        mMainData.setmCODataList(adapterData);
        for (COResponse mCoResponse : adapterData) {
            dialogString.add(mCoResponse.getcONM());
        }
        showItemDialog(dialogString, onCompanyDialogItemClick);
    }

    @Override
    public void setPZData(List<PZResponse> adapterData) {
        dialogString.clear();
        mMainData.setmPZDataList(adapterData);
        for (PZResponse mPZResponse : adapterData) {
            dialogString.add(mPZResponse.getmPZNM());
        }
        showItemDialog(dialogString, onFavtoryAreaDialogItemClick);
    }

    @Override
    public void setDPNMData(List<DPResponse> adapterData) {
        dialogString.clear();
        mMainData.setmDPDataList(adapterData);
        for (DPResponse mDPResponse : adapterData) {
            dialogString.add(mDPResponse.getmDPNM());
        }
        showItemDialog(dialogString, onFactoryClassDialogItemClick);
    }

    @Override
    public void setEQKDData(List<SHIFTResponse> adapterData) {
        dialogString.clear();
        mMainData.setmSHIFTDataList(adapterData);
        for (SHIFTResponse mSHIFTResponse : adapterData) {
            dialogString.add(mSHIFTResponse.getmShift());
        }
        showItemDialog(dialogString, onClassUnitDialogItemClick);
    }

    @Override
    public void setTYPEData(List<TYPEResponse> adapterData) {
        dialogString.clear();
        mMainData.setmTYPEDataList(adapterData);
        for (TYPEResponse mTYPEResponse : adapterData) {
            dialogString.add(mTYPEResponse.getmType());
        }
        showItemDialog(dialogString, onShootTypeCategoryDialogItemClick);
    }

    @Override
    protected void onPause() {
        super.onPause();
        dismissProgressDialog();
    }

    //如果能改成用retrofit加rxjava最好，已經嘗試過，可能有缺什麼，不過緊急所以先求功能
    @Override
    public void onUploadFile(final ArrayList<String> uriList, String type, final String sid) {
        uploadPath = mPresenter.onJudgmentPath(pathCompany, pathFactoryArea,pathFactoryClass,pathClass,pathShootType);
        dismissProgressDialog();
        showProgressDialog(type);
        new Thread(new Runnable() {
            @Override
            public void run() {
                String path1 = uploadPath;

                OkHttpClient client = new OkHttpClient().newBuilder()
                        .connectTimeout(60, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                MultipartBody.Builder buildernew = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("_sid", sid)
                        .addFormDataPart("path",path1);

                for (String path : uriList) {
                    File uploadFile = new File(path);
                    buildernew.addFormDataPart("file", uploadFile.getName(),
                            RequestBody.create(MediaType.parse("multiparty/form-data"), path));
                }
                RequestBody body = buildernew.build();

                Request request = new Request.Builder()
                        .addHeader("Accept","*/*")
                        .url("https://webapp.fpcitc.com.tw/SOP/api/FileUpload/fileUpload")
                        .method("POST", body)
                        .build();

                try {
                    Response response = client.newCall(request).execute();
                    final String responsemessage = response.message();
                    final String responsebody = response.body().string();
                    JSONObject json = null;
                    try {
                        json = new JSONObject(responsebody);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    Log.e("response", responsebody);
//                    dismissProgressDialog();
                    if (json.get("success").equals("true"))
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                            showDialogMessage("上傳完成");

                        }
                    });
//                        Log.e("isSuccess",json.get("IsSuccess").toString());
                    mPresenter.onLogoutSid(sidData);                //登出sid
                } catch (final IOException | JSONException e) {
                    MainActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            dismissProgressDialog();
                            e.printStackTrace();
                            showDialogMessage("上傳失敗");
                            Log.e("error", "" + e.getMessage());
                        }
                    });
                }
            }
        }).start();
    }

    private DialogInterface.OnClickListener onCompanyDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textCompany.setText(mMainData.getmCODataList().get(which).getcONM());
            pathCompany = mMainData.getmCODataList().get(which).getcONM();
            mChooseDeviceItemData.setCompany(mMainData.getmCODataList().get(which).getcONM());
            mChooseDeviceItemData.setCompanyId(mMainData.getmCODataList().get(which).getcO());


        }
    };
    private DialogInterface.OnClickListener onFavtoryAreaDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textFactory.setText(mMainData.getmPZDataList().get(which).getmPZNM());
            pathFactoryArea = mMainData.getmPZDataList().get(which).getmPZNM();
            mChooseDeviceItemData.setFactoryAreaName(mMainData.getmPZDataList().get(which).getmPZNM());
            mChooseDeviceItemData.setFactoryAreaId(mMainData.getmPZDataList().get(which).getmPZ());

        }
    };
    private DialogInterface.OnClickListener onFactoryClassDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textUnit.setText(mMainData.getmDPDataList().get(which).getmDPNM());
            pathFactoryClass = mMainData.getmDPDataList().get(which).getmDPNM();
            mChooseDeviceItemData.setFactoryClassCode(mMainData.getmDPDataList().get(which).getmDP());
            mChooseDeviceItemData.setFactoryClass(mMainData.getmDPDataList().get(which).getmDPNM());
            mChooseDeviceItemData.setProductionPlantId(mMainData.getmDPDataList().get(which).getmPMFCT());

        }
    };

    private DialogInterface.OnClickListener onClassUnitDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textClass.setText(mMainData.getmSHIFTDataList().get(which).getmShift());
            pathClass = mMainData.getmSHIFTDataList().get(which).getmShift();
            mChooseDeviceItemData.setDeviceCategory(mMainData.getmSHIFTDataList().get(which).getmShift());
        }
    };

    private DialogInterface.OnClickListener onShootTypeCategoryDialogItemClick = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            textShootType.setText(mMainData.getmTYPEDataList().get(which).getmType());
            pathShootType = mMainData.getmTYPEDataList().get(which).getmType();
            mChooseDeviceItemData.setShootType(mMainData.getmTYPEDataList().get(which).getmType());
        }
    };


}
