/*
   Copyright 2016 Evgeny A. Kudryashov.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package com.noname.monopolyebank.fragments;


import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.noname.monopolyebank.R;
import com.noname.monopolyebank.domain.Player;

import java.util.ArrayList;
import java.util.List;


public class CreateGameFragment extends Fragment {
    public final static int MAX_PLAYERS = 8;
    private static String TAG = "CreateGameFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        final View currentView = inflater.inflate(R.layout.fragment_create_game, container, false);
        final LinearLayout mainContainer = (LinearLayout) currentView.findViewById(R.id.createGamePlayersContainer);

        // Adding players
        Button addPlayer = (Button) currentView.findViewById(R.id.createGameButtonAddPlayer);
        addPlayer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Subtract a banker player, s/he is in another place
                int idx = mainContainer.getChildCount();
                if (idx >= MAX_PLAYERS - 1) {
                    Toast toast = Toast.makeText(getContext(),
                            getString(R.string.players_limit) + MAX_PLAYERS,
                            Toast.LENGTH_SHORT);
                    toast.show();
                    return;
                }

                // Layouts
                final LinearLayout layout = new LinearLayout(getContext());
                layout.setOrientation(LinearLayout.HORIZONTAL);

                // Params
                LinearLayout.LayoutParams general = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                LinearLayout.LayoutParams generalWeightedMargins = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        1f);
                LinearLayout.LayoutParams imagesParams = new LinearLayout.LayoutParams(
                        ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                imagesParams.gravity = Gravity.CENTER;

                // Elements
                EditText name = new EditText(getContext());
                name.setHint(R.string.player_name);

                ImageButton deleteButton = new ImageButton(getContext());
                deleteButton.setImageResource(R.drawable.ic_delete_black_24dp);
                deleteButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        mainContainer.removeView(layout);
                    }
                });

                layout.addView(name, generalWeightedMargins);
                layout.addView(deleteButton, imagesParams);
                mainContainer.addView(layout, general);
            }
        });

        Button next = (Button) currentView.findViewById(R.id.createGameButtonRegisterNfc);
        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<String> names = new ArrayList<>(MAX_PLAYERS);
                EditText bankerText = (EditText) currentView.findViewById(R.id.createGameEditTextBankerName);
                EditText gameText = (EditText) currentView.findViewById(R.id.createGameEditTextGameName);
                EditText moneyText = (EditText) currentView.findViewById(R.id.createGameEditTextInitialMoney);
                String bankerName = bankerText.getText().toString().trim();
                String gameName = gameText.getText().toString().trim();
                // Check game name
                if (gameName.isEmpty()) {
                    Toast toast = Toast.makeText(getContext(), R.string.empty_game_name, Toast.LENGTH_SHORT);
                    toast.show();
                    return;
                }
                // Check banker
                if (bankerName.isEmpty()) {
                    Toast toast = Toast.makeText(getContext(), R.string.banker_name_empty, Toast.LENGTH_SHORT);
                    toast.show();
                    return;
                }
                // Other players
                String enteredName;
                for (int i = 0; i < mainContainer.getChildCount(); ++i) {
                    EditText editText = (EditText) ((LinearLayout) mainContainer.getChildAt(i)).getChildAt(0);
                    enteredName = editText.getText().toString().trim();
                    if (enteredName.isEmpty()) {
                        Toast toast = Toast.makeText(getContext(), "Please, fill all players' names", Toast.LENGTH_SHORT);
                        toast.show();
                        return;
                    }
                    names.add(enteredName);
                }
                int money;
                try {
                    money = Integer.parseInt(moneyText.getText().toString().trim());
                } catch (Exception e) {
                    money = 1500;
                }
                // TODO check length of names
                // TODO container size (const)
                List<Player> players = new ArrayList<>(8);
                players.add(new Player(bankerName, true));
                for (String name : names) {
                    players.add(new Player(name));
                }
                // TODO force enable NFC
                // Everything is OK change start registering
                CardRegisterFragment cardRegisterFragment = new CardRegisterFragment();
                cardRegisterFragment.setPlayers(players);
                cardRegisterFragment.setGameName(gameName);
                cardRegisterFragment.setBalance(money);
                FragmentChangeListener fc = (FragmentChangeListener) getActivity();
                fc.replaceFragment(cardRegisterFragment, true);
            }
        });

        return currentView;
    }

    @Override
    public String toString() {
        return TAG;
    }

}
