package com.rv.im.mvp.presenter;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.ruiwenliu.wrapper.util.permission.RxPermission;
import com.rv.im.Constants;
import com.rv.im.ImSetting;
import com.rv.im.call.Jitsi_pre;
import com.rv.im.db.service.ChatMessageServiceImp;
import com.rv.im.db.service.IChatMessageService;
import com.rv.im.db.table.ChatMessage;
import com.rv.im.enums.CallTypeEnum;
import com.rv.im.enums.MessageStatusEnum;
import com.rv.im.enums.MessageTypeEnum;
import com.rv.im.mvp.view.IChatView;
import com.rv.im.photopicker.SelectModel;
import com.rv.im.photopicker.intent.PhotoPickerIntent;
import com.rv.im.util.UploadEngine;
import com.rv.im.view.SelectFileDialog;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class ChatPresenterImp implements IChatPresenter {

    private WeakReference<Context> weakReference = null;

    private IChatView chatView = null;

    private String fromUserId;
    private String toUserId;
    private String fromUserName;
    private String toUserName;

    public ChatPresenterImp(Context context, IChatView chatView) {
        this.weakReference = new WeakReference<>(context);
        this.chatView = chatView;
    }


    @Override
    public void setChatInfo(String fromUserId, String fromUserName, String toUserId, String toUserName) {
        this.fromUserId = fromUserId;
        this.toUserId = toUserId;
        this.fromUserName = fromUserName;
        this.toUserName = toUserName;
    }

    @Override
    public void sendVoice(String filePath, int timeLen) {

        if (TextUtils.isEmpty(filePath)) {
            return;
        }
        ChatMessage message = new ChatMessage();
        message.setMessageType(MessageTypeEnum.VOICE);
        message.setUpLoadStatus(1);
        message.setUploadSchedule(0);
        message.setContent("");
        message.setFilePath(filePath);
        message.setTimeLen(timeLen);
        sendMessage(message);
    }

    @SuppressLint("CheckResult")
    @Override
    public void clickPicPicker(boolean isCamera) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission((Activity) weakReference.get()).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.CAMERA,
                    Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                if (aBoolean == true) {
                    if (isCamera) {
                        clickCamera();
                    } else {
                        openAlbum();
                    }
                } else {
                    Toast.makeText(weakReference.get(), "用户授权失败", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            if (isCamera) {
                clickCamera();
            } else {
                openAlbum();
            }
        }
    }

    @Override
    public void openAlbum() {
        ArrayList<String> imagePaths = new ArrayList<>();
        PhotoPickerIntent intent = new PhotoPickerIntent(weakReference.get());
        intent.setSelectModel(SelectModel.MULTI);
        // 已选中的照片地址， 用于回显选中状态
        intent.setSelectedPaths(imagePaths);
        ((Activity) weakReference.get()).startActivityForResult(intent, IChatView.REQUEST_CODE_PICK_PHOTO);
    }

    private String[] cameraPermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};

    private String[] choiceFilePermissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};

    private File cameraSavePath = null;

    @Override
    public void clickCamera() {

        cameraSavePath = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Uri uri = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //第二个参数为 包名.fileprovider
            uri = FileProvider.getUriForFile(weakReference.get(), weakReference.get().getPackageName() + ".fileprovider", cameraSavePath);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            uri = Uri.fromFile(cameraSavePath);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        ((Activity) weakReference.get()).startActivityForResult(intent, IChatView.REQUEST_CODE_CAMERA);
    }

    @Override
    public void sendText(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        ChatMessage message = new ChatMessage();
        message.setMessageType(MessageTypeEnum.TEXT);
        message.setFromUserId(fromUserId);
        message.setFromUserName(fromUserName);
        message.setContent(text);
        sendMessage(message);
    }

    @Override
    public void realDial(int type, String meetUrl) {
        ChatMessage message = new ChatMessage();
        if (type == 1) {// 语音通话
            message.setMessageType(MessageTypeEnum.VOLTE_CALL);
            message.setContent("发起语音通话");
            message.setCallType(CallTypeEnum.CONNECT_VOICE);
        } else {// 视频通话
            message.setMessageType(MessageTypeEnum.VIDEO_CALL);
            message.setContent("发起视频通话");
            message.setCallType(CallTypeEnum.CONNECT_VIDEO);
        }

        if (!TextUtils.isEmpty(meetUrl)) {
            message.setFilePath(meetUrl);
        }
        sendMessage(message);
        Intent intent = new Intent(weakReference.get(), Jitsi_pre.class);
        if (type == 1) {
            intent.putExtra("isvoice", true);
        } else {
            intent.putExtra("isvoice", false);
        }
        intent.putExtra("fromuserid", fromUserId);
        intent.putExtra("touserid", toUserId);
        intent.putExtra("username", toUserName);
        if (!TextUtils.isEmpty(meetUrl)) {
            intent.putExtra("meetUrl", meetUrl);
        }
        weakReference.get().startActivity(intent);
    }

    private void sendMessage(ChatMessage message) {

        message.setFromUserId(fromUserId);
        message.setFromUserName(fromUserName);
        message.setToUserName(toUserName);
        message.setRead(true);
        message.setFromId("android");
        message.setToUserId(toUserId);
        message.setPackId(UUID.randomUUID().toString().replaceAll("-", ""));
        message.setTimeSend(System.currentTimeMillis());
        message.setMessageStatus(MessageStatusEnum.SENDING);
        getDbService().addMessage(message);
        chatView.addMessage(message);
        readySend(message);
    }

    @Override
    public void readySend(ChatMessage message) {
        if (message.getMessageType() == MessageTypeEnum.PIC.getType() || message.getMessageType() == MessageTypeEnum.FILE.getType()
                || message.getMessageType() == MessageTypeEnum.VOICE.getType()) {
            if (message.getUpLoadStatus() == 1 || message.getUpLoadStatus() == 3) {
                UploadEngine.uploadImFile(weakReference.get(), ImSetting.getImToken(), fromUserId, toUserId, message, mUploadResponse);
            } else {
                sendMsgBroad(message);
            }
        } else {
            sendMsgBroad(message);
        }
    }

    @Override
    public void sendMsgBroad(ChatMessage message) {
        Intent intent = new Intent();
        intent.setAction(Constants.ACTIONS.ACTION_SEND_RECEIVER);
        intent.setPackage(weakReference.get().getPackageName());
        intent.putExtra(Constants.KEYS.KEY_MESSAGE_TARGET, toUserId);
        intent.putExtra(Constants.KEYS.KEY_MESSAGE_CONTENT, message.toJsonString());
        weakReference.get().sendBroadcast(intent);
    }

    @Override
    public void album(ArrayList<String> stringArrayListExtra, boolean isOriginal) {
        if (isOriginal) {// 原图发送，不压缩
            Log.e("zq", "原图发送，不压缩，开始发送");
            for (int i = 0; i < stringArrayListExtra.size(); i++) {
                sendImage(new File(stringArrayListExtra.get(i)));
            }
            Log.e("zq", "原图发送，不压缩，发送结束");
            return;
        }

        List<File> fileList = new ArrayList<>();
        for (int i = 0; i < stringArrayListExtra.size(); i++) {
            // gif动图不压缩，
            if (stringArrayListExtra.get(i).endsWith("gif")) {
                fileList.add(new File(stringArrayListExtra.get(i)));
                stringArrayListExtra.remove(i);
            } else {
                // Luban只处理特定后缀的图片，不满足的不处理也不走回调，
                // 只能挑出来不压缩，
                List<String> lubanSupportFormatList = Arrays.asList("jpg", "jpeg", "png", "webp", "gif");
                boolean support = false;
                for (int j = 0; j < lubanSupportFormatList.size(); j++) {
                    if (stringArrayListExtra.get(i).endsWith(lubanSupportFormatList.get(j))) {
                        support = true;
                        break;
                    }
                }
                if (!support) {
                    fileList.add(new File(stringArrayListExtra.get(i)));
                    stringArrayListExtra.remove(i);
                }
            }
        }

        if (fileList.size() > 0) {
            for (File file : fileList) {// 不压缩的部分，直接发送
                sendImage(file);
            }
        }

        Luban.with(weakReference.get())
                .load(stringArrayListExtra)
                .ignoreBy(100)// 原图小于100kb 不压缩
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                        Log.e("zq", "开始压缩");
                    }

                    @Override
                    public void onSuccess(File file) {
                        sendImage(file);
                    }

                    @Override
                    public void onError(Throwable e) {

                    }
                }).launch();// 启动压缩
    }

    public IChatMessageService getDbService() {
        return ChatMessageServiceImp.getInstance(weakReference.get());
    }

    @Override
    public void sendImage(File file) {
        if (file == null && cameraSavePath != null) {
            file = cameraSavePath;
        }
        if (!file.exists()) {
            return;
        }
//        if (isAuthenticated()) {
//            return;
//        }
//        long fileSize = file.length();
        ChatMessage message = new ChatMessage();
        message.setMessageType(MessageTypeEnum.PIC);
        message.setUpLoadStatus(1);
        message.setUploadSchedule(0);
//        message.setContent("");
        String filePath = file.getAbsolutePath();
        message.setFilePath(filePath);
        message.setTimeSend(System.currentTimeMillis());
//        message.setF((int) fileSize);
//        int[] imageParam = FileDataHelper.getImageParamByIntsFile(filePath);
//        message.setLocation_x(String.valueOf(imageParam[0]));
//        message.setLocation_y(String.valueOf(imageParam[1]));
//        message.setIsReadDel(isReadDel);
//        mChatMessages.add(message);
//        mChatContentView.notifyDataSetInvalidated(true);

        sendMessage(message);
    }

    @SuppressLint("CheckResult")
    @Override
    public void clickFile() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new RxPermission((Activity) weakReference.get()).request(
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE).subscribe(aBoolean -> {
                if (aBoolean == true) {
                    showFileChoiceDialog();
                } else {
                    Toast.makeText(weakReference.get(), "用户授权失败", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            showFileChoiceDialog();
        }
    }

    private void showFileChoiceDialog() {
        SelectFileDialog dialog = new SelectFileDialog(weakReference.get(), new SelectFileDialog.OptionFileListener() {
            @Override
            public void option(List<File> files) {
                if (files != null && files.size() > 0) {
                    for (int i = 0; i < files.size(); i++) {
                        sendFile(files.get(i));
                    }
                }
            }

            @Override
            public void intent() {
                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                intent.addCategory(Intent.CATEGORY_OPENABLE);
                ((Activity) weakReference.get()).startActivityForResult(intent, IChatView.REQUEST_CODE_SELECT_FILE);
            }

        });
        dialog.show();
    }

    @Override
    public void setMsgRead(String targetUserId) {
        getDbService().setMsgRead(targetUserId);
    }

    @Override
    public void sendFile(File file) {
        if (!file.exists()) {
            return;
        }
//        if (isAuthenticated()) {
//            return;
//        }
        ChatMessage message = new ChatMessage();
        message.setMessageType(MessageTypeEnum.FILE);
        message.setUpLoadStatus(1);
        message.setUploadSchedule(0);
        message.setContent("");
        message.setTimeSend(System.currentTimeMillis());
        String filePath = file.getAbsolutePath();
        message.setFilePath(filePath);
        sendMessage(message);
    }

//
//    private SendMessageListener listener = new AbstractMsgListener() {
//
//        @Override
//        public void sendMsgSuccess(String receiptId) {
//            chatView.sendMessSuccess(receiptId);
//        }
//
//        @Override
//        public void receiverMsg(String message) {
//            if (!TextUtils.isEmpty(message)) {
//                ChatMessage chatMessage = ChatMessage.json2Message(message);
//                if (chatMessage != null && TextUtils.equals(chatMessage.getFromUserId(), toUserId)) {
//                    chatView.receiverMsg(chatMessage);
//                }
//            }
//        }
//
//        @Override
//        public void sendMsgFailure(String receiptId) {
//            chatView.sendMessFailure(receiptId);
//        }
//    };


    private UploadEngine.ImFileUploadResponse mUploadResponse = new UploadEngine.ImFileUploadResponse() {

        @Override
        public void onSuccess(String toUserId, ChatMessage message) {
            ChatMessageServiceImp.getInstance(weakReference.get()).setUpSuccess(message.getPackId(), message.getContent());
            chatView.upSuccess(toUserId, message);
        }

        @Override
        public void onFailure(String toUserId, ChatMessage message) {
            ChatMessageServiceImp.getInstance(weakReference.get()).setUpFailure(message.getPackId());
            chatView.upFailure(toUserId, message);
        }

        @Override
        public void onUpProgress(String toUserId, ChatMessage message) {
            ChatMessageServiceImp.getInstance(weakReference.get()).setUpProgress(message.getPackId(), message.getUploadSchedule());
            chatView.upProgress(toUserId, message);
        }
    };
}
