package com.lemenzo.clock.worldclock;

import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

public final class WorldClockRepository {
    private final SharedPreferences p;
    private static volatile List<SearchEntry> searchIndex;
    private static final class SearchEntry {
        final String zone; final String text; final String citySort;
        SearchEntry(String zone,String text,String citySort){this.zone=zone;this.text=text;this.citySort=citySort;}
    }

    public WorldClockRepository(Context c) {
        p = c.getSharedPreferences("world_clock", 0);
    }

    public List<String> zones() {
        ArrayList<String> out = new ArrayList<>();
        try {
            JSONArray a = new JSONArray(p.getString("zones", "[]"));
            for (int i = 0; i < a.length(); i++) out.add(a.getString(i));
        } catch (Exception ignored) {}
        if (out.isEmpty()) out.add(ZoneId.systemDefault().getId());
        return out;
    }

    public void add(String z) {
        List<String> a = zones();
        if (!a.contains(z)) a.add(z);
        write(a);
    }

    public void remove(String z) {
        List<String> a = zones();
        a.remove(z);
        if (a.isEmpty()) a.add(ZoneId.systemDefault().getId());
        write(a);
    }

    private void write(List<String> a) {
        JSONArray j = new JSONArray();
        for (String z : a) j.put(z);
        p.edit().putString("zones", j.toString()).apply();
    }

    private static List<SearchEntry> index(){
        List<SearchEntry> cached=searchIndex;if(cached!=null)return cached;
        synchronized(WorldClockRepository.class){
            cached=searchIndex;if(cached!=null)return cached;
            Locale locale=Locale.getDefault();ArrayList<SearchEntry> built=new ArrayList<>();
            for(String z:ZoneId.getAvailableZoneIds()){
                String city=WorldClockFormatter.city(z).toLowerCase(locale);
                built.add(new SearchEntry(z,WorldClockFormatter.searchText(z,locale),city));
            }
            built.sort(Comparator.comparing(e->e.citySort));
            searchIndex=Collections.unmodifiableList(built);return searchIndex;
        }
    }

    public static List<String> search(String q) {
        String needle=q==null?"":q.trim().toLowerCase(Locale.ROOT);
        ArrayList<String> out=new ArrayList<>();
        for(SearchEntry e:index())if(needle.isEmpty()||e.text.contains(needle))out.add(e.zone);
        return out;
    }
}
