File size: 6,193 Bytes
d45ec63
56a9838
d45ec63
 
 
 
b838c58
 
 
 
560823b
 
d45ec63
6d2d129
 
d45ec63
56a9838
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d45ec63
e21d599
d45ec63
 
3a2866a
f625376
 
 
 
 
 
3a2866a
 
255e3c4
3a2866a
f625376
 
eaae921
535ec3b
eaae921
 
 
 
255e3c4
eaae921
255e3c4
eaae921
255e3c4
3e6686b
535ec3b
3a2866a
eaae921
255e3c4
 
535ec3b
255e3c4
eaae921
 
 
 
 
 
3e6686b
 
902260e
255e3c4
3e6686b
 
902260e
535ec3b
3e6686b
255e3c4
 
2d08297
 
c1ae968
 
 
 
 
2d08297
 
560823b
c1ae968
 
2d08297
3e6686b
 
560823b
050fd9f
b7c2e71
3e6686b
 
f625376
07e3fbe
 
 
f625376
07e3fbe
f625376
07e3fbe
f625376
07e3fbe
f625376
07e3fbe
f625376
07e3fbe
f625376
07e3fbe
f625376
07e3fbe
f625376
07e3fbe
 
d45ec63
 
 
 
bf92156
 
 
 
 
 
 
fac5a9c
2eee45f
d45ec63
2dc08a5
 
ac6561c
 
b54d7d2
050fd9f
b54d7d2
 
 
3e6686b
3a2866a
f625376
f1a728b
f625376
3e6686b
 
5dc6e46
3e6686b
07e3fbe
 
f625376
07e3fbe
f625376
d45ec63
56a9838
 
d45ec63
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
import streamlit as st
import streamlit.components.v1 as components

from config import DEFAULT_ICON
from shared_page import common_page_config

from domain.playoffs import (
    PLAYOFF_WEEK_TO_NAME,
    CURRENT_PLAYOFF_WEEK,
)
from login import check_password
from data_storage import update_selection, get_user_team

from load_options import load_options, PlayerOption, display_player


def set_selectbox_readonly():
    components.html(
        """
<script>
    function formatSelectBox() {
        const matches = window.parent.document.querySelectorAll("input");
        matches.forEach((input) => {
            input.setAttribute("readonly", "true");
        });

    }
    formatSelectBox();

</script>
    """,
        width=0,
        height=0,
    )


def format_player_option(player_opt: PlayerOption) -> str:
    return f"{player_opt.full_name} - {player_opt.team}"


def position_cell(
    week: str,
    pos_str: str,
    pos_idx: int,
    options_map: dict[str, dict[int, list[PlayerOption]]],
    existing_selection_map,
    team_filter: list[str],
):
    pos_label = f"{week}-{pos_str}-{pos_idx}"
    selected_id = existing_selection_map.get(pos_label)
    options_list = options_map[pos_str][int(week)]
    if team_filter:
        options_list = [x for x in options_list if x.team in team_filter or str(selected_id) == str(x.gsis_id)]
    non_locked_options = [x for x in options_list if not x.is_locked()]
    disabled = False
    # get selected player by id from options
    try:
        selected_player = next(v for v in options_list if str(selected_id) == str(v.gsis_id))
    except Exception:
        selected_player = PlayerOption.empty_player()

    if int(week) > CURRENT_PLAYOFF_WEEK:
        # future week, no options
        options = []
        selected_option_idx = 0
        disabled = True
    elif int(week) < CURRENT_PLAYOFF_WEEK or selected_player.is_locked():
        # past week, can't change
        options = [selected_player]
        selected_option_idx = 0
        disabled = True
    else:
        options = non_locked_options
        # set to index of current select.  This should exist, but try-except for safety
        try:
            selected_option_idx = non_locked_options.index(selected_player)
        except ValueError:
            selected_option_idx = 0

    selected_player_from_box = st.selectbox(
        pos_str,
        options=options,
        format_func=format_player_option,
        index=selected_option_idx,
        key=pos_label,
        disabled=disabled,
    )
    if selected_player_from_box and int(week) == CURRENT_PLAYOFF_WEEK:
        if selected_player_from_box.gsis_id and selected_player_from_box.gsis_id != selected_id:
            if selected_player_from_box.is_locked():
                st.warning("Sorry player's game has already started", icon="🚨")
                display_player(selected_player)
                return
            elif selected_player_from_box.gsis_id in existing_selection_map.values():
                st.warning("Player already in lineup.  Please choose another.", icon="🚨")
                display_player(selected_player)
                return
            else:
                update_and_save_selection(pos_label, selected_player_from_box.gsis_id),
        display_player(selected_player_from_box)
    else:
        display_player(selected_player)


def update_and_save_selection(pos_label: str, selection_id: str):
    update_selection(st.session_state["logged_in_user"], pos_label, selection_id, st.session_state["db_client"])
    st.rerun()


def week_selections(week, player_options, existing_selections, team_filter: list[str]):
    selection_cols = st.columns(8)

    with selection_cols[0]:
        position_cell(week, "QB", 1, player_options, existing_selections, team_filter)
    with selection_cols[1]:
        position_cell(week, "RB", 1, player_options, existing_selections, team_filter)
    with selection_cols[2]:
        position_cell(week, "RB", 2, player_options, existing_selections, team_filter)
    with selection_cols[3]:
        position_cell(week, "WR", 1, player_options, existing_selections, team_filter)
    with selection_cols[4]:
        position_cell(week, "WR", 2, player_options, existing_selections, team_filter)
    with selection_cols[5]:
        position_cell(week, "TE", 1, player_options, existing_selections, team_filter)
    with selection_cols[6]:
        position_cell(week, "K", 1, player_options, existing_selections, team_filter)
    with selection_cols[7]:
        position_cell(week, "DEF", 1, player_options, existing_selections, team_filter)


def get_page():
    page_title = "Select Your Team"
    st.set_page_config(page_title=page_title, page_icon=DEFAULT_ICON, layout="wide")
    common_page_config()
    try:
        logged_in = check_password()
    except Exception:
        st.write("Sorry, error logging in.  Please try again.")
        st.stop()

    if not logged_in:
        st.write("Sorry, you must be logged in first to play")
        st.stop()

    st.title(page_title)

    if st.button("Refresh Data"):
        st.rerun()
    try:
        existing_selections = get_user_team(st.session_state["logged_in_user"], st.session_state["db_client"])
    except Exception:
        st.write("Sorry error occurred loading team. Please try refreshing page.")
        st.stop()

    player_options = load_options()
    # TODO - make more robust than just picking week 1 defenses but should work for now
    team_options_for_filter = sorted([x.team for x in player_options["DEF"][CURRENT_PLAYOFF_WEEK]])
    team_filter = st.multiselect("Filter for NFL teams", team_options_for_filter)

    for week in range(1, 5):
        existing_week_selections = {k: v for k, v in existing_selections.items() if k[0] == str(week)}
        st.header(PLAYOFF_WEEK_TO_NAME[week])
        if week < CURRENT_PLAYOFF_WEEK:
            with st.expander("Show Previous Week"):
                week_selections(week, player_options, existing_week_selections, team_filter)
        else:
            week_selections(week, player_options, existing_week_selections, team_filter)

    set_selectbox_readonly()


if __name__ == "__main__":
    get_page()