package ai.pai.lensman.service;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Binder;
import android.os.IBinder;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;

import ai.pai.lensman.bean.OrderBean;
import ai.pai.lensman.db.Preferences;
import ai.pai.lensman.utils.BoxUrlContainer;
import ai.pai.lensman.utils.Constants;
import ai.pai.lensman.utils.HttpPostTask;
import ai.pai.lensman.utils.UrlContainer;

public class OrderDealService extends Service {

    private ArrayList<OrderBean> orderList;

    private static final String TAG = "czy";

    @Override
    public IBinder onBind(Intent intent) {
        return new OrderServiceBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (!isQueueEmpty()) {
            return START_STICKY;
        }
        startQuery();
        return START_STICKY;
    }

    private void startQuery() {
        HashMap<String, String> params = new HashMap<>();
        params.put("user_id", Preferences.getInstance().getLensManId());
        new HttpPostTask(params) {

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d(TAG, "startQuery order list = " + response);
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        JSONObject data = json.getJSONObject("data");
                        JSONArray orders = data.getJSONArray("files");
                        if (orders != null && orders.length() > 0) {
                            orderList = new ArrayList<OrderBean>();
                            for (int k = 0; k < orders.length(); k++) {
                                JSONObject orderObj = orders.getJSONObject(k);
                                OrderBean bean = new OrderBean();

                                orderList.add(bean);
                            }
                        }
                        return true;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                dealOrder();
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                new Timer().schedule(
                        new TimerTask() {
                            @Override
                            public void run() {
                                startQuery();
                            }
                        }, 15000
                );
            }
        }.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.QUERY_ORIGIN_ORDER_URL);

    }

    private void dealOrder() {
        if (!isQueueEmpty()) {
            OrderBean orderBean = orderList.get(0);
            fetchOriginFromBox(orderBean);
        } else {
            startQuery();
        }
    }

    private void fetchOriginFromBox(OrderBean orderBean) {
        HashMap<String, String> params = new HashMap<>();
        params.put("lensman", Preferences.getInstance().getLensManId());
        params.put("session", orderBean.photoBean.sessionId);
        params.put("name", orderBean.photoBean.photoName);
        new HttpPostTask(params) {
            OrderBean bean = new OrderBean();

            @Override
            protected boolean parseResponse(String response) {
                LogHelper.d(TAG, "fetchOriginFromBox get response string = " + response);
                try {
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if (status == 200) {
                        JSONObject data = json.getJSONObject("data");
                        //TODO
                    }
                    return true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostFail() {
                super.onPostFail();
                orderList.remove(bean);
                dealOrder();
            }

            @Override
            protected void onPostSuccess() {
                super.onPostSuccess();
                new SavePhotoTask(bean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), bean);
            }
        }.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), BoxUrlContainer.FETCH_ORIGIN_URL);

    }

    private void uploadOrigin(OrderBean bean) {
        new UploadTask(bean).executeOnExecutor(ThreadExecutor.getInstance().getExecutor());
    }

    private boolean isQueueEmpty() {
        return (orderList == null || orderList.size() == 0);
    }

    public class OrderServiceBinder extends Binder {

        public OrderDealService getService() {
            return OrderDealService.this;
        }

    }

    class SavePhotoTask extends AsyncTask<OrderBean, Integer, Boolean> {

        private OrderBean orderBean;

        public SavePhotoTask(OrderBean bean) {
            this.orderBean = bean;
        }

        @Override
        protected Boolean doInBackground(OrderBean... params) {

            String path = BoxUrlContainer.PHOTO_PATH_PREFIX_URL + orderBean.photoBean.photoPath;
            LogHelper.d(TAG, "保存照片到本地，图片链接地址为" + path);
            FileOutputStream fOut = null;
            HttpURLConnection conn = null;
            InputStream inStream = null;
            try {
                URL url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                inStream = conn.getInputStream();
                if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + orderBean.photoBean.sessionId + File.separator + Constants.ORIGIN_DIR_NAME;
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    File file = new File(dir, orderBean.photoBean.photoName);
                    fOut = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len;
                    while ((len = inStream.read(buffer)) != -1) {
                        fOut.write(buffer, 0, len);
                        fOut.flush();
                    }
                    fOut.flush();
                    LogHelper.d(TAG, "保存照片到本地，图片保存至" + file.getAbsolutePath() + "图片大小为" + file.length() + "字节\n\n");
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    inStream.close();
                    conn.disconnect();
                    fOut.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            if (result) {
                uploadOrigin(orderBean);
            } else {
                orderList.remove(orderBean);
                dealOrder();
            }
        }
    }

    public class UploadTask extends AsyncTask<Void, Integer, Boolean> {

        private static final String TAG = "czy";
        private OrderBean bean;

        public UploadTask(OrderBean bean) {
            this.bean = bean;
        }

        @Override
        protected Boolean doInBackground(Void... params) {
            for (int k = 0; k < 5; k++) {
                try {
                    String dirPath = ai.pai.lensman.utils.Constants.APP_IMAGE_DIR + File.separator + bean.photoBean.sessionId
                            + File.separator + Constants.ORIGIN_DIR_NAME;
                    File dir = new File(dirPath);
                    dir.mkdirs();
                    File photo = new File(dir, bean.photoBean.photoName);
                    LogHelper.d(TAG, "上传照片 第" + k + "次尝试" + bean);
                    if (photo.exists() && photo.isFile()) {
                        PhotoUploadUtils photoUploadUtils = new PhotoUploadUtils(UrlContainer.ORIGIN_PHOTO_UPLOAD_URL + "?timestamp=" + System.currentTimeMillis());
                        photoUploadUtils.addFileParameter("photo", photo);
                        photoUploadUtils.addTextParameter("user_id", bean.photoBean.lensmanId);
                        photoUploadUtils.addTextParameter("session_id", bean.photoBean.sessionId);
                        photoUploadUtils.addTextParameter("photo_id", String.valueOf(bean.photoBean.photoId));
                        photoUploadUtils.addTextParameter("nickname", Preferences.getInstance().getUserName());

                        String result = new String(photoUploadUtils.send(), "UTF-8");
                        JSONObject resultObj = new JSONObject(result);
                        if (resultObj.getInt("status") == 200) {
                            LogHelper.d(TAG, "上传 UploadTask upload result ok ");
                            return true;
                        }
                    } else {
                        return false;
                    }

                } catch (Exception e) {
                    LogHelper.d(TAG, "上传发生异常 UploadTask :" + bean + " error:" + e);
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            if (result) {
                LogHelper.d(TAG, "上传 UploadTask " + bean + "  success ");
                orderList.remove(bean);
                dealOrder();
            } else {
                LogHelper.d(TAG, "上传 UploadTask " + bean + "  fail ");
            }
        }
    }



}
