package org.ntlab.radishforandroidstudio.cactusClient.views;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.app.Fragment;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;


import net.arnx.jsonic.JSON;
import net.arnx.jsonic.TypeReference;

import org.ntlab.radishforandroidstudio.R;
import org.ntlab.radishforandroidstudio.cactusClient.Cactus;
import org.ntlab.radishforandroidstudio.cactusClient.connections.CharactersFragmentConnection;
import org.ntlab.radishforandroidstudio.cactusClient.connections.PlayersConnection;
import org.ntlab.radishforandroidstudio.cactusClient.models.Account;
import org.ntlab.radishforandroidstudio.cactusClient.models.Character;
import org.ntlab.radishforandroidstudio.cactusClient.models.Player;
import org.ntlab.radishforandroidstudio.framework.network.CallBack;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

public class CharactersFragment extends Fragment {

    private CharactersFragmentConnection connection;
    private String instanceId;
    private Account account;
    private Cactus cactus;
    private ArrayList<String> characterIds = new ArrayList<>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        instanceId = getArguments().getString("instanceId");

        cactus = (Cactus) getActivity().getApplication();
        account = cactus.getMyAccount();

        connection = new CharactersFragmentConnection(instanceId);

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.characters_fragment, container, false);
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {

        Button button = (Button) getActivity().findViewById(R.id.chooseInstances);
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                FragmentManager manager = getFragmentManager();
                FragmentTransaction transaction = manager.beginTransaction();
                transaction.replace(R.id.fragment_place, new InstancesFragment());
                transaction.commit();
            }
        });

        // ListViewをセット
        final ArrayAdapter adapter = new ArrayAdapter(this.getContext(), android.R.layout.simple_list_item_1, characterIds);
        ListView listView = (ListView) view.findViewById(R.id.list);
        listView.setAdapter(adapter);

        CharactersFragmentConnection con = new CharactersFragmentConnection(instanceId);
//        con.addQueryParam("accountID", account.getUniqueID());
        con.setCallBack(new CallBack() {
            private Context context;
            public CallBack setContext(Context context) {
                this.context = context;
                return this;
            }
            @Override
            public void onResponse(String response) {
                Map<String, Character> characters = JSON.decode(response, new TypeReference<HashMap<String, Character>>(){});
                for (String characterId : characters.keySet()) {
                    characterIds.add(characterId);
                    final ArrayAdapter adapter = new ArrayAdapter(context, android.R.layout.simple_list_item_1, characterIds);
                    ListView listView = (ListView)view.findViewById(R.id.list);
                    listView.setAdapter(adapter);
                }
            }
        }.setContext(this.getContext()));
        con.doGet();
        // セルを選択されたら詳細画面フラグメント呼び出す
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            private Context context;
            @Override
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                PlayersConnection con = new PlayersConnection();
                con.addFormParam("instanceID", instanceId);
                con.addFormParam("characterID", characterIds.get(position));
                con.setCallBack(new CallBack() {
                    @Override
                    public void onResponse(String response) {
                        Map<String, Player> player = JSON.decode(response, new TypeReference<HashMap<String, Player>>(){});
                        // TODO: 複数帰ってきた，もしくは帰ってこなかったときの処理

                        // プレイ画面へ
                        Bundle bundle = new Bundle();
                        bundle.putSerializable("characterId", characterIds.get(position));
                        bundle.putSerializable("player", (Player)player.values().toArray()[0]);
                        String[] splitedUri = ((String)(player.keySet().toArray()[0])).split("/");
                        bundle.putString("playerId", splitedUri[splitedUri.length-1]);
                        bundle.putString("instanceId", instanceId);
                        PlayerFragment fragment = new PlayerFragment();

                        fragment.setArguments(bundle);
                        FragmentManager manager = getFragmentManager();
                        FragmentTransaction transaction = manager.beginTransaction();
                        transaction.replace(R.id.fragment_place, fragment);
                        transaction.addToBackStack(null);
                        characterIds.clear();
                        transaction.commit();
                    }
                });

                con.doPost();
            }
        });
    }
}