package com.liamfruzyna.android.racetimer.fragments;

import android.app.Fragment;
import android.app.FragmentManager;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.liamfruzyna.android.racetimer.AppData;
import com.liamfruzyna.android.racetimer.Fab;
import com.liamfruzyna.android.racetimer.objects.Event;
import com.liamfruzyna.android.racetimer.objects.Meet;
import com.liamfruzyna.android.racetimer.R;
import com.liamfruzyna.android.racetimer.objects.Runner;

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

/**
 * Created by mail929 on 9/13/14.
 * A fragement that shows a meets data and how runners performed in the events
 *
 * [fixed] WARNING: THE CODE IN THIS CLASS IS ESPECIALLY BAD. CLASSES THAT REPEAT INSIDE OF THEMSELVES CAN CAUSE HEADACHES, MIGRAINES, AND SEIZURES
 * -T-O-D-O- meet health and safety standards
 */
public class MeetFragment extends Fragment
{

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        View view = inflater.inflate(R.layout.meet, container, false);

        //init view widgets
        final Meet meet = AppData.meets.get(getArguments().getInt("key"));
        final Fab fab = (Fab) view.findViewById(R.id.fab);
        TextView name = (TextView) view.findViewById(R.id.meetName);
        TextView shortName = (TextView) view.findViewById(R.id.shortName);
        final Spinner eventSpinner = (Spinner) view.findViewById(R.id.eventSpinner);
        final TextView level = (TextView) view.findViewById(R.id.eventLevel);
        final TextView distance = (TextView) view.findViewById(R.id.eventDistance);
        final ListView runner = (ListView) view.findViewById(R.id.runnerList);
        final Button start = (Button) view.findViewById(R.id.start);

        //set up fab (Floating Action Button)
        fab.setFabDrawable(getResources().getDrawable(R.drawable.ic_action_add));
        fab.setFabColor(getResources().getColor(R.color.fab_blue));
        fab.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                //takes you to add a new event when clicked
                Fragment tf = new AddEventFragment();
                Bundle args = new Bundle();
                args.putInt("key", meet.id);
                tf.setArguments(args);
                FragmentManager fragmentManager = getFragmentManager();
                fragmentManager.beginTransaction().replace(R.id.container, tf).commit();
            }
        });

        //creates a list of events level and distance to fill out the spinner
        List<String> events = new ArrayList<String>();
        for(int i = 0; i < meet.events.size(); i++)
        {
            events.add(meet.events.get(i).level + " " + meet.events.get(i).distance);
        }

        //setup spinner
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, events);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        eventSpinner.setAdapter(adapter);

        //sets textviews to appropriate data
        name.setText(meet.name);
        shortName.setText(meet.shortName);

        //waits for the spinner to be changed
        eventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
            {
                //locally saves event
                final Event event = meet.events.get(eventSpinner.getSelectedItemPosition());

                //sets more textviews based on the event
                level.setText(event.level);
                distance.setText(Double.toString(event.distance));

                //disable the start button if the event has been run so no repetitive data
                if(event.run == true)
                {
                    start.setEnabled(false);
                    start.getBackground().setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY);
                }

                //creates a list of runner data [name, teams string, time]
                final List<String[]> data = new ArrayList<String[]>();
                for(int i = 0; i < event.runners.size(); i++)
                {
                    //saves runner locally
                    Runner r = AppData.runners.get(event.runners.get(i));

                    //builds a string of teams
                    StringBuilder sb = new StringBuilder();
                    for(int j = 0; j < r.teams.size(); j++)
                    {
                        sb.append(AppData.teams.get(r.teams.get(j)).shortName);
                        if(j < r.teams.size()-1)
                        {
                            sb.append(" ");
                        }
                    }

                    //gets time
                    String time = "0";
                    for(int j = 0; j < r.times.size(); j++)
                    {
                        if(event.id == r.times.get(j).eventId && r.times.get(j).checkPoints.size() > 0)
                        {
                            time = r.times.get(j).checkPoints.get(r.times.get(j).checkPoints.size() - 1);
                        }
                    }

                    data.add(new String[]{r.name, sb.toString(), time});
                }

                //listview of runners times
                runner.setAdapter(new ArrayAdapter<String[]>(getActivity(), R.layout.runner_event_listitem, R.id.name, data)
                {
                    public View getView(final int position, View convertView, ViewGroup parent)
                    {
                        //basic setup
                        View view;
                        if(convertView == null)
                        {
                            LayoutInflater infl = (LayoutInflater) getActivity().getSystemService(getActivity().LAYOUT_INFLATER_SERVICE);
                            convertView = infl.inflate(R.layout.runner_event_listitem, parent, false);
                        }
                        view = super.getView(position, convertView, parent);

                        //init view widgets
                        TextView name = (TextView) view.findViewById(R.id.name);
                        TextView teams = (TextView) view.findViewById(R.id.runnerTeam);
                        TextView time = (TextView) view.findViewById(R.id.runnerTime);

                        //set textviews with appropriate data
                        name.setText(data.get(position)[0]);
                        teams.setText(data.get(position)[1]);
                        time.setText(data.get(position)[2]);
                        return view;
                    }
                });

                //listens for runner to be selected then goes to that runners page
                runner.setOnItemClickListener(new AdapterView.OnItemClickListener()
                {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l)
                    {
                        Fragment rf = new RunnerFragment();
                        Bundle args = new Bundle();
                        args.putInt("key", event.runners.get(i));
                        rf.setArguments(args);
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.container, rf).commit();
                    }
                });

                //listen for runner to be clicked
                start.setOnClickListener(new View.OnClickListener()
                {
                    public void onClick(View v)
                    {
                        //sets the event as run
                        event.run = true;
                        //brings you to that runners event
                        Fragment tf = new InRaceFragment();
                        Bundle args = new Bundle();
                        args.putInt("key", meet.id);
                        args.putInt("event", event.id);
                        tf.setArguments(args);
                        FragmentManager fragmentManager = getFragmentManager();
                        fragmentManager.beginTransaction().replace(R.id.container, tf).commit();
                    }
                });
            }

            //this is required, its just a waste of space for me :(
            @Override
            public void onNothingSelected(AdapterView<?> parentView){}

        });
        return view;
    }
}
