package com.mogo.cloud.location.third.core;

import android.util.Log;

import com.elegant.spi.AbstractDelegateManager;
import com.elegant.spi.core.visitor.ServiceClassValue;
import com.mogo.cloud.location.LocationConfig;

public class LocationDelegateManager extends AbstractDelegateManager<LocationServiceProvider>
        implements AbstractDelegateManager.DelegateListener<Class<? extends LocationServiceProvider>> {

    private static final String TAG = "LocationDelegateManager";

    private LocationServiceProvider locationServiceProvider;

    private boolean loaded = false;

    public static LocationDelegateManager getInstance(){
        return SingletonHolder.INSTANCE;
    }

    private static final class SingletonHolder{
        private static final LocationDelegateManager INSTANCE = new LocationDelegateManager();
    }

    private LocationDelegateManager(){
    }

    public void loadDelegates() {
        if (!loaded) {
            loadDelegateClasses(LocUploadConfig.instance().getContext(),
                    LocationServiceProvider.class, this);
            loaded = true;
        }
    }

    public void unloadDelegates() {
        if (loaded) {
            if(locationServiceProvider != null){
                if (LocationConfig.isPrintLog) {
                    Log.d(TAG, String.format("注销 LocationServiceProvider -> %s",
                            locationServiceProvider.getClass().getName()));
                }
                locationServiceProvider = null;
            }
            loaded = false;
        }
    }

    @Override
    public void onDelegate(String unit, Class<? extends LocationServiceProvider> p) {
        try {
            locationServiceProvider = ServiceClassValue.of(p, unit)
                    .accept(SERVICE_CLASS_VISITOR, unit);
            if (LocationConfig.isPrintLog) {
                Log.d(TAG, String.format("Biz id is [%s], 注册 LocationServiceProvider -> %s ",
                        unit, p.getName()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public LocationServiceProvider getLocationServiceProvider(){
        return locationServiceProvider;
    }
}
