package kr.co.hanwha.hifive.data.source;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.Random;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.data.model.MaximData;
import kr.co.hanwha.hifive.data.model.MaximRoot;
import kr.co.hanwha.hifive.data.source.contract.MaximDataSource;
import kr.co.hanwha.hifive.network.HFNetworkUtil;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkCallback;
import kr.co.hanwha.hifive.network.hanwha.HanwhaNetworkError;

public class MaximDataRepository implements MaximDataSource {
    private static MaximDataRepository sInstance = null;
    private static ArrayList<MaximData> sListMaximData;

    public static MaximDataRepository getInstance() {
        if (sInstance == null) {
            sInstance = new MaximDataRepository();
        }
        return sInstance;
    }

    public static void destroyInstance() {
        sInstance = null;
    }

    @Override
    public void clearData() {
        if (sListMaximData != null) sListMaximData.clear();
        sListMaximData = null;
    }

    @Override
    public void requestMaximList(@NonNull Context context, @Nullable final HanwhaNetworkCallback callback) {
        String encryption_member_id = MemberDataRepository.getInstance().getEncryptionMemberId();
        HFNetworkUtil networkUtil = new HFNetworkUtil();
        networkUtil.requestMaximList(context, encryption_member_id, new HanwhaNetworkCallback<MaximRoot>() {
            @Override
            public void onSuccess(MaximRoot response) {
                if (response != null) {
                    sListMaximData = response.getListRandomMaxims();
                }
                callback.onSuccess(sListMaximData);
            }

            @Override
            public void onFailure(HanwhaNetworkError error) {
                callback.onFailure(error);
            }

            @Override
            public void onPreExecute() {
                callback.onPreExecute();
            }

            @Override
            public void onPostExecute() {
                callback.onPostExecute();
            }
        });
    }

    @Override
    public MaximData getRandomMaximData(@NonNull Context context) {
        if (sListMaximData != null && sListMaximData.size() > 0) {
            Random random = new Random();
            int index = random.nextInt(sListMaximData.size());
            return sListMaximData.get(index);
        }


        return new MaximData(context.getString(R.string.maxim_contents), context.getString(R.string.maxim_source));
    }

}
