package com.fun.airhornprank.tool;

import android.content.res.AssetManager;

import com.fun.airhornprank.PrankSkin;
import com.fun.airhornprank.data.Mydata;

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

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Mytools {
    private static ExecutorService executorService;


    public static void runIO(Runnable task) {
        getExecutorService().execute(task);
    }

    private static ExecutorService getExecutorService() {
        if (executorService == null) {
            executorService = Executors.newSingleThreadExecutor();
        }
        return executorService;
    }

    private static JSONArray loadJson(String filename) {
        String json;
        try {
            AssetManager assetManager = PrankSkin.app.getAssets();
            InputStream inputStream = assetManager.open(filename);
            int size = inputStream.available();
            byte[] buffer = new byte[size];
            inputStream.read(buffer);
            inputStream.close();
            json = new String(buffer, StandardCharsets.UTF_8);
            return new JSONArray(json);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static List<Mydata> getList(String filename) {
        List<Mydata> dataList = new ArrayList<>();
        try {
            JSONArray jsonObject = loadJson(filename);
            for (int a = 0; a < jsonObject.length(); a++) {
                JSONObject list = jsonObject.getJSONObject(a);
                String categoryName = list.getString("categoryName");
                String categoryUrl = list.getString("categoryUrl");
                JSONArray classArray = list.getJSONArray("list");
                for (int i = 0; i < classArray.length(); i++) {
                    JSONObject item = classArray.getJSONObject(i);
                    Mydata allData = new Mydata();
                    allData.setCategoryname(categoryName);
                    allData.setCategoryUrl(categoryUrl);
                    allData.setLike(false);
                    allData.setRank(false);
                    allData.setTitle(item.getString("title"));
                    allData.setMp3Url(item.getString("mp3Url"));
                    allData.setPreUrl(item.getString("preUrl"));
                    dataList.add(allData);
                }
            }

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

        return dataList;
    }


}
