package com.halo.assistant.fragment.user;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.view.MenuItem;

import androidx.annotation.NonNull;

import com.gh.gamecenter.common.base.fragment.WaitingDialogFragment;
import com.gh.gamecenter.common.constant.EntranceConsts;
import com.gh.gamecenter.common.utils.UploadImageUtils;
import com.gh.gamecenter.CropImageActivity;
import com.gh.gamecenter.R;
import com.gh.gamecenter.common.retrofit.Response;
import com.gh.gamecenter.common.view.cropbox.CropBoxStyle;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.json.JSONObject;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.schedulers.Schedulers;
import retrofit2.HttpException;

/**
 * 裁剪图片（上传头像）
 */
public class UserPortraitCropImageActivity extends CropImageActivity {

    private SharedPreferences sp;

    @Override
    protected void handleMessage(Message msg) {
        switch (msg.what) {
            case 0:
                toast("上传成功");
                break;
            case 1:
                toast("上传失败");
                break;
            case 2:
                toast("修改太频繁，请稍后再试");
                break;
            case 3:
                toast("图片违规");
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sp = PreferenceManager.getDefaultSharedPreferences(this);
    }

    @Override
    protected void saveImage() {
        final WaitingDialogFragment postDialog = WaitingDialogFragment.newInstance(getString(R.string.post_img));
        postDialog.show(getSupportFragmentManager(), null);
        final String path = getCacheDir() + File.separator + System.currentTimeMillis() + ".jpg";
        Observable.create((ObservableOnSubscribe<String>) emitter -> {
                    boolean isSuccess = savePicture(path);
                    if (isSuccess) {
                        UploadImageUtils.INSTANCE.uploadImage(UploadImageUtils.UploadType.icon, path, new UploadImageUtils.OnUploadImageListener() {
                            @Override
                            public void onSuccess(@NotNull String imageUrl) {
                                emitter.onNext(imageUrl);
                                emitter.onComplete();
                            }

                            @Override
                            public void onError(@Nullable Throwable e) {
                                if (e != null) {
                                    emitter.onError(e);
                                } else {
                                    emitter.onError(new IllegalStateException("upload image error"));
                                }
                            }

                            @Override
                            public void onProgress(long total, long progress) {
                                int percent = (int) (100 * (progress / (float) total));
                                if (percent >= 100) percent = 99;
                                if (postDialog != null) {
                                    postDialog.uploadWaitingHint("图片上传中 " + percent + "%");
                                }
                            }
                        });
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(Schedulers.io())
                .subscribe(new Response<String>() {
                    @Override
                    public void onResponse(String url) {
                        try {
                            if (postDialog != null) postDialog.dismissAllowingStateLoss();
                            mBaseHandler.sendEmptyMessage(0);

                            String iconCount = sp.getString("updateIconCount", null);

                            long l = System.currentTimeMillis();
                            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd", Locale.CHINA);
                            String time = format.format(new Date(l));

                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("time", time);

                            if (TextUtils.isEmpty(iconCount)) {
                                jsonObject.put("count", 1);
                            } else {
                                JSONObject json = new JSONObject(iconCount);
                                String lastTime = json.getString("time");
                                if (lastTime.equals(time)) {
                                    jsonObject.put("count", json.getInt("count") + 1);
                                } else {
                                    jsonObject.put("count", 1);
                                }
                            }

                            sp.edit().putString("updateIconCount", jsonObject.toString()).apply();

                            Intent data = new Intent();
                            data.putExtra(EntranceConsts.KEY_URL, url);
                            setResult(RESULT_OK, data);
                            finish();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(HttpException e) {
                        if (postDialog != null) postDialog.dismissAllowingStateLoss();
                        try {
                            if (e != null && e.code() == HttpURLConnection.HTTP_FORBIDDEN && e.response().errorBody() != null) {
                                JSONObject object = new JSONObject(e.response().errorBody().string());
                                String detail = object.getString("detail");
                                if ("too frequent".equals(detail)) {
                                    mBaseHandler.sendEmptyMessage(2);
                                } else if ("INVALID PICTURE".equals(detail)) {
                                    mBaseHandler.sendEmptyMessage(3);
                                } else {
                                    mBaseHandler.sendEmptyMessage(1);
                                }
                            } else {
                                mBaseHandler.sendEmptyMessage(1);
                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();
                            mBaseHandler.sendEmptyMessage(1);
                        }
                    }
                });

    }

    // 用户头像压缩规则
    public boolean savePicture(String path) {
        Bitmap clip = mCropImageCustom.clip();
        try {
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(path)));
            clip.compress(Bitmap.CompressFormat.WEBP, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @NonNull
    public static Intent getIntent(Context context, String picturePath, String entrance) {
        Intent intent = new Intent(context, UserPortraitCropImageActivity.class);
        intent.putExtra(EntranceConsts.KEY_PATH, picturePath);
        intent.putExtra(EntranceConsts.KEY_ENTRANCE, entrance);
        intent.putExtra(EntranceConsts.KEY_IMAGE_CROP_STYLE, CropBoxStyle.Circle.INSTANCE);
        return intent;
    }
}
