package me.kareluo.imaging;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.location.Address;
import android.location.Geocoder;
import android.media.ExifInterface;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import me.kareluo.imaging.core.IMGMode;
import me.kareluo.imaging.core.IMGPath;
import me.kareluo.imaging.core.IMGText;
import me.kareluo.imaging.core.file.IMGDecoder;
import me.kareluo.imaging.core.file.IMGFileDecoder;
import me.kareluo.imaging.core.util.IMGUtils;

/**
 * Created by felix on 2017/11/14 下午2:26.
 */

public class IMGEditActivity extends IMGEditBaseActivity {
    private static final String TAG = IMGEditActivity.class.getSimpleName();

    private static final int MAX_WIDTH = 2048;

    private static final int MAX_HEIGHT = 2048;

    private String date = "", photoAddress = "";
    private Uri uri;
    private int destType;
    private String markString = "", imageUrl;


    @Override
    public void onCreated() {

    }


    @Override
    public Bitmap getBitmap() {
        Intent intent = getIntent();
        if (intent == null) {
            return null;
        }

        imageUrl = getIntent().getExtras().getString("imageUrl");
        Log.d(TAG, "getBitmap: imageUrl===>" + imageUrl);
        enableEdit = getIntent().getBooleanExtra("enableEdit", true);
        markString = getIntent().getExtras().getString("markString");
        uri = getIntent().getParcelableExtra("uri");
        destType = getIntent().getIntExtra("destType", 0);
        Bitmap bitmap;
        IMGDecoder decoder = new IMGFileDecoder(Uri.parse(imageUrl));
        if (decoder == null) {
            return null;
        }

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        options.inJustDecodeBounds = true;

        decoder.decode(options);
        int lineWidth = (int) ((options.outWidth * 1.0 / MAX_WIDTH) * 40);
        //        Log.e("LineWidth",lineWidth+"");
        lineWidth = lineWidth > 40 ? 40 : lineWidth;
        IMGPath.setLineWidth(lineWidth);

        if (options.outWidth > MAX_WIDTH) {
            options.inSampleSize = IMGUtils.inSampleSize(Math.round(1f * options.outWidth / MAX_WIDTH));
        }

        if (options.outHeight > MAX_HEIGHT) {
            options.inSampleSize = Math.max(options.inSampleSize,
                    IMGUtils.inSampleSize(Math.round(1f * options.outHeight / MAX_HEIGHT)));
        }

        options.inJustDecodeBounds = false;

        bitmap = decoder.decode(options);
        if (bitmap == null) {
            return null;
        }

        try {
            Matrix mat = new Matrix();
            Geocoder geocoder = new Geocoder(this);
            ExifInterface ei = new ExifInterface(imageUrl);
            int orientation = ei.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                mat.postRotate(90);
            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                mat.postRotate(180);

            } else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                mat.postRotate(270);

            }
            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);
            float[] latLong = new float[2];
            boolean hasAddressInfo = ei.getLatLong(latLong);
            String dateTime = ei.getAttribute(ExifInterface.TAG_DATETIME);
            if (!TextUtils.isEmpty(dateTime)) {
                if (dateTime.length() >= 16) {
                    dateTime = dateTime.substring(0, 4) + "-" + dateTime.substring(5, 7) + "-" + dateTime.substring(8, 16);
                }
                date = dateTime;
            } else {
                //相机拍的照片
                date = convertTimestamp2Date();
            }

            if (hasAddressInfo) {
                List<Address> addresses = geocoder.getFromLocation(latLong[0], latLong[1], 1);
                for (Address address : addresses) {
                    if ("北京市".equals(address.getLocality()) || "天津市".equals(address.getLocality()) ||
                            "重庆市".equals(address.getLocality()) || "上海市".equals(address.getLocality())) {
                        photoAddress = address.getLocality();
                    } else {
                        photoAddress = address.getAdminArea() + address.getLocality();
                    }
                }
            }

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

        return bitmap;
    }


    public String convertTimestamp2Date() {
        Long timestamp = System.currentTimeMillis();
        String pattern = "yyyy-MM-dd HH:mm";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
        return simpleDateFormat.format(new Date(timestamp));
    }


    @Override
    public void onText(IMGText text) {
        mImgView.addStickerText(text);
    }

    @Override
    public void onModeClick(IMGMode mode) {
        IMGMode cm = mImgView.getMode();
        if (cm == mode) {
            mode = IMGMode.NONE;
        }
        mImgView.setMode(mode);
        updateModeUI();

        if (mode == IMGMode.CLIP) {
            setOpDisplay(OP_CLIP);
        }
    }

    @Override
    public void onUndoClick() {
        IMGMode mode = mImgView.getMode();
        if (mode == IMGMode.DOODLE) {
            mImgView.undoDoodle();
        } else if (mode == IMGMode.MOSAIC) {
            mImgView.undoMosaic();
        }
    }

    @Override
    public void onCancelClick() {
        finish();
    }

    @Override
    public void onDoneClick() {
        String path = Uri.parse(imageUrl).getPath();
        if (!TextUtils.isEmpty(path)) {
            Bitmap bitmap = mImgView.saveBitmap();
            if (bitmap != null) {
                FileOutputStream fout = null;
                try {
                    fout = new FileOutputStream(path);
                    bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fout);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } finally {
                    if (fout != null) {
                        try {
                            fout.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                Toast.makeText(IMGEditActivity.this, "保存图片成功", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent();
                intent.setData(uri);
                intent.putExtra("destType", destType);
                intent.putExtra("path", imageUrl);
                setResult(99, intent);
                finish();
                return;
            }
        }
        setResult(RESULT_CANCELED);
        finish();
    }

    @Override
    public void onCancelClipClick() {
        mImgView.cancelClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onDoneClipClick() {
        mImgView.doClip();
        setOpDisplay(mImgView.getMode() == IMGMode.CLIP ? OP_CLIP : OP_NORMAL);
    }

    @Override
    public void onResetClipClick() {
        mImgView.resetClip();
    }

    @Override
    public void onRotateClipClick() {
        mImgView.doRotate();
    }

    @Override
    public void onColorChanged(int checkedColor) {
        mImgView.setPenColor(checkedColor);
    }

    @Override
    public String getMarkString() {
        String ret = "";
        if (!(TextUtils.isEmpty(markString) || "null".equals(markString))) {
            ret += markString + " : ";
        }
        if (!(TextUtils.isEmpty(photoAddress) || "null".equals(photoAddress))) {
            ret += photoAddress + " : ";
        }
        if (!(TextUtils.isEmpty(date) || "null".equals(date))) {
            ret += date + " : ";
        }
        if (ret.length() >= 3) {
            ret = ret.substring(0, ret.length() - 3);
        }
        return ret;
    }
}
