package com.oqpo.api.service;

import com.oqpo.api.constant.ApiConstants;
import com.oqpo.api.entity.PushData;
import com.oqpo.api.entity.oper.MemberEntity;
import com.oqpo.api.enums.PushMessage;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.web.interceptor.HeaderRequestInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.codehaus.jackson.map.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PushService  extends CommonService {

    @Autowired
    private UserMngMapper userMngMapper;


    @Value("${push.firebase_server_key}")
    private String firebase_server_key;

    @Value("${push.firebase_api_url}")
    private String firebase_api_url;

    // jobType po 주문, rtn 반품  , reuUnqNo 관련번호
    public PushData makePushData(String brandId, String jobType, String relUnqNo) throws JSONException, InterruptedException {

        PushData  pushData = new PushData();

        List<MemberEntity> targetList = userMngMapper.selectPushTargetList(brandId);

        if (targetList.size() > 0) {

            JSONObject bodySA = new JSONObject();
            //List<JSONArray> arrayListSA = new ArrayList<JSONArray>();
            JSONArray arraySA = new JSONArray();

            for (int i = 0 ; i < targetList.size() ;i++) {
                MemberEntity tempEntity = targetList.get(i);
                arraySA.put(tempEntity.getAppReg());
            }

            bodySA.put("registration_ids", arraySA);
            bodySA.put("content_available", ApiConstants.PUSH_CONTENT_AVAILABLE);
            bodySA.put("priority", ApiConstants.PUSH_PRIORITY);
            bodySA.put("apns-push-type", ApiConstants.PUSH_APNS_PUSH_TYPE);
            bodySA.put("apns-priority", ApiConstants.PUSH_APNS_PRIORITY);

            JSONObject dataSA = new JSONObject();

            try {
                if ("PO".equals(jobType)) {
                    dataSA.put("title", "매장주문");
                } else {
                    dataSA.put("title", "매장반품");
                }
                if ("PO".equals(jobType)) {
                    dataSA.put("body", PushMessage.PUSH_REQ.getName());
                    dataSA.put("data", "PO");
                } else {
                    dataSA.put("body", PushMessage.PUSH_RTN.getName());
                    dataSA.put("data", "RTN");
                }

                //dataSA.put("click_action", ApiConstants.PUSH_ACTION);
                //dataSA.put("data", entity.getPushLandingCd());
                //dataSA.put("relNo", entity.getLinkUrl());
                bodySA.put("data", dataSA);
            } catch (Exception e) {
            }

            pushData.setBodyData(bodySA.toString());
            //pushData.setPushNo(entity.getPushNo());
            //pushData.setPushSize(targetList.size());

        }

        return pushData;
    }


    public ArrayList<ClientHttpRequestInterceptor> pushSet(HttpEntity<String> entity) {

        ArrayList<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();

        log.info("firebase_server_key ============>" + firebase_server_key);
        interceptors.add(new HeaderRequestInterceptor("Authorization", "key=" + firebase_server_key));
        interceptors.add(new HeaderRequestInterceptor("Content-Type", "application/json;charset=UTF-8"));

        return interceptors;
    }


    public void pushSend(String brandId, String jobType, String relUnqNo) {
        log.info("=========================push run");
        try {
            PushData  pushData = makePushData(brandId, jobType, relUnqNo);
            String bodyData = pushData.getBodyData();
            for (int i = 0; i < ApiConstants.PUSH_RETRY; i++) {
                URL url = new URL(firebase_api_url);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key=" + firebase_server_key);
                conn.setConnectTimeout(ApiConstants.URLCONN_TIME_OUT);
                conn.setReadTimeout(ApiConstants.URLCONN_TIME_OUT);
                conn.setDoOutput(true);

                OutputStream os = conn.getOutputStream();
                os.write(bodyData.getBytes("UTF-8"));
                os.flush();
                os.close();
                int responseCode = conn.getResponseCode();
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();

                    while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                    }
                    in.close();
                    // 결과 처리
                    Map<String,Object> responsMap = new ObjectMapper().readValue(response.toString(), HashMap.class);

                    int retSuccess = (int) responsMap.get("success");
                    log.info("========================connect retSuccess" + Integer.toString(retSuccess));
                    int retError = (int) responsMap.get("failure");
                    log.info("========================connect erroor" + Integer.toString(retError));
                    break;
                } else {
                    Thread.sleep(1000);
                    log.info("========================connect erroor" + Integer.toString(i));
                }

            }

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


    }




}
