package jp.odakyu.toiletsignage.logic;

import android.content.Context;
import android.os.Environment;

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

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import jp.odakyu.toiletsignage.constants.ToiletConstants;
import jp.odakyu.toiletsignage.file.FileUtil;
import jp.odakyu.toiletsignage.info.ToiletInfo;
import jp.odakyu.toiletsignage.json.USBToiletDefaultJson;
import jp.odakyu.toiletsignage.log.Logger;

/**
 * Created by agentec on 2017/12/08.
 */

public class MainLogic {
    private static final String TOILET_INFO_JSON = "/toiletInfo.json";
    private static final String KEY_TOILET_ARRAY = "toiletArray";
    private static final String TAG = "MainLogic";

    /**
     * USBドライブからトイレ情報ファイルを外部ストレージ「Download」フォルダにコピー
     * @param context ToiletApplication Context
     * @return VALUE_GET_USB_INFO_SUCCESS:成功、
     * VALUE_GET_USB_INFO_VALIDATION_FAIL:バリデーションチェック失敗
     * VALUE_GET_USB_INFO_FAIL:トイレ情報ファイル取得失敗
     *
     * @throws IOException Fileオブジェクト取得及びコピー時の例外
     * @throws JSONException Json情報取得からの例外
     *
     */
    public static int getToiletDefaultInfo(Context context) throws IOException, JSONException {
        String []rootStorageDirectory = getExtSdCardPathsForActivity(context);

        File downloadFilePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        String copyFilePath = downloadFilePath.getPath() + TOILET_INFO_JSON;

        for(String directoryName:rootStorageDirectory) {
            String jsonFilePath = directoryName + TOILET_INFO_JSON;
            Logger.d(TAG, jsonFilePath);
            File uspJsonFile = new File(jsonFilePath);

            if (uspJsonFile.exists() && uspJsonFile.isFile()) {
                FileUtil.fileCopy(jsonFilePath, copyFilePath);
                break;
            } else {
                Logger.w(TAG, "usb json file not exists = " + jsonFilePath);
            }
        }

        if (new File(copyFilePath).exists()) {
            JSONObject jsonObject = new JSONObject(FileUtil.getStringFromFile(copyFilePath));
            JSONArray jsonArray = jsonObject.getJSONArray(KEY_TOILET_ARRAY);
            ArrayList<USBToiletDefaultJson> toiletDefaultJsonArray = new ArrayList<>();
            boolean isValidation = false;
            for (int i = 0; i < jsonArray.length(); i++){
                USBToiletDefaultJson toiletDefaultJson = new USBToiletDefaultJson(jsonArray.getJSONObject(i));
                isValidation = toiletDefaultJson.validation(jsonArray.getJSONObject(i));

                if (isValidation) {
                    toiletDefaultJsonArray.add(toiletDefaultJson);
                } else {
                    break;
                }
            }
            if (!isValidation) {
                return ToiletConstants.VALUE_GET_USB_INFO_VALIDATION_FAIL;
            }
            if (toiletDefaultJsonArray.size() != 0) {
                ToiletInfo.getInstance().setToiletDefaultJsonArray(toiletDefaultJsonArray);
            } else {
                return ToiletConstants.VALUE_GET_USB_INFO_FAIL;
            }
        } else {
            return ToiletConstants.VALUE_GET_USB_INFO_FAIL;
        }

        return ToiletConstants.VALUE_GET_USB_INFO_SUCCESS;
    }

    /**
     * 外部ストレージのパス情報を取得
     * @param context ToiletApplication Context
     * @return Storage直下のPath List
     */
    private static String[] getExtSdCardPathsForActivity(Context context) {
        List<String> pathList = new ArrayList<>();
        for (File file : context.getExternalFilesDirs("external")) {
            if (file != null) {
                int index = file.getAbsolutePath().lastIndexOf("/Android/data");
                if (index < 0) {
                    Logger.w("AmazeFileUtils", "Unexpected external file dir: " + file.getAbsolutePath());
                } else {
                    String path = file.getAbsolutePath().substring(0, index);
                    try {
                        String canonicalPath = new File(path).getCanonicalPath();
                        pathList.add(canonicalPath);
                    } catch (IOException e) {
                        // Keep non-canonical path.
                        Logger.e(TAG, e.getLocalizedMessage(), e);
                    }
                }
            }
        }
        if (pathList.isEmpty()) pathList.add("/storage/sdcard1");
        return pathList.toArray(new String[0]);
    }
}
