"""
PREDICTING THE RESULT OF SHOTS BY MOHAMED SALAH
"""
import io
import pandas as pd
import matplotlib.pyplot as plt
import plotly.express as px
from urllib.request import urlopen
from bs4 import BeautifulSoup as bs
"""
# Importing DATA from understat
"""
"""
a="https://understat.com/player/1250"
page=urlopen(a)
url=bs(page,"html.parser")
obj=url.findAll("script")[3].text
obj
start=obj.index("\\")
stop=obj.index("')")
obj=obj[start:stop]
obj
obj=obj.encode("utf8").decode("unicode_escape")
import json
p=json.loads(obj)
shots=pd.json_normalize(p) 
print(shots)

"""
"""
shots.to_csv('shots.csv')
files.download('shots.csv')
"""
shots=pd.read_csv('../input/mohamed-salah-shots-understat/shots.csv')
shots.info()
shots=shots.apply(pd.to_numeric,errors="ignore")
shots=shots.loc[(shots["season"]>=2020)]
shots
"""
# Visualization

"""
# Import plotting libraries
import seaborn as sns
import plotly.express as px
import matplotlib.pyplot as plt
import plotly.graph_objects as go
from matplotlib.patches import Arc
from plotly.subplots import make_subplots
px.scatter(data_frame=shots, x="player_assisted", title="Mohamed Salah assisters", color="result")
px.histogram(data_frame=shots, x="player_assisted", color="result", title="ASSISTING PLAYERS")
shots.columns
import numpy as np
import pandas as pd
import seaborn as sns
sns.set_palette('husl')
import matplotlib.pyplot as plt
%matplotlib inline
import plotly.express as px

from sklearn import metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
shots2= shots.loc[:,['minute', 'result', 'X', 'Y', 'xG', 'situation', 'shotType',
       'h_goals', 'a_goals', 'lastAction'],]
  sns.pairplot(shots2, hue="result", palette="Set1")

import json
import matplotlib.pyplot as plt
from matplotlib.patches import Arc
x=[0,1.15]
y=[0,0.74]
x_mid=x[1]/2
y_mid=y[1]/2
background_color = "black"
line_color = "white"
line_width = 2
def pitch(x, y, background_color="black", line_color="white", line_width=2.):
  fig=plt.figure(facecolor=background_color, figsize=(12, 7))
  ax=fig.add_subplot(111, facecolor=background_color)
  plt.plot([x[0],x[0]],[y[0],y[1]], color=line_color, linewidth=2)
  plt.plot([x[1],x[1]],[y[0],y[1]], color=line_color, linewidth=2)
  plt.plot([x[0],x[1]],[y[1],y[1]], color=line_color, linewidth=2)
  plt.plot([x[0],x[1]],[y[0],y[0]], color=line_color, linewidth=2)
  plt.plot([x_mid,x_mid],[y[0],y[1]], color=line_color, linewidth=2)
  ## Left Penalty box
  plt.plot([x[0],x[0]+0.18],[y_mid+0.22,y_mid+0.22], color=line_color, linewidth=2)
  plt.plot([x[0],x[0]+0.18],[y_mid-0.22,y_mid-0.22], color=line_color, linewidth=2)
  plt.plot([x[0]+0.18,x[0]+0.18],[y_mid-0.22,y_mid+0.22], color=line_color, linewidth=2)
  ## Right Penalty box
  plt.plot([x[1],x[1]-0.18],[y_mid+0.22,y_mid+0.22], color=line_color, linewidth=2)
  plt.plot([x[1],x[1]-0.18],[y_mid-0.22,y_mid-0.22], color=line_color, linewidth=2)
  plt.plot([x[1]-0.18,x[1]-0.18],[y_mid-.22,y_mid+.22], color=line_color, linewidth=2)
  ## left 6 yard box
  plt.plot([x[0],x[0]+0.06],[y_mid+0.06,y_mid+0.06], color=line_color, linewidth=2)
  plt.plot([x[0],x[0]+0.06],[y_mid-0.06,y_mid-0.06], color=line_color, linewidth=2)
  plt.plot([x[0]+0.06,x[0]+0.06],[y_mid-0.06,y_mid+0.06], color=line_color, linewidth=2)
  ## right 6 yard box
  plt.plot([x[1],x[1]-0.06],[y_mid+0.06,y_mid+0.06], color=line_color, linewidth=2)
  plt.plot([x[1],x[1]-0.06],[y_mid-0.06,y_mid-0.06], color=line_color, linewidth=2)
  plt.plot([x[1]-0.06,x[1]-0.06],[y_mid-0.06,y_mid+0.06], color=line_color, linewidth=2)
  ##centre cirle and penanlty spot
  centre_circle=plt.Circle((x_mid,y_mid),0.1, color=line_color, fill=False, linewidth=2)
  centre_spot=plt.Circle((x_mid,y_mid),0.005,color=line_color,fill=True, linewidth=2)
  leftspot=plt.Circle((x[0]+0.12,y_mid),0.005,color=line_color,fill=True, linewidth=2)
  rightspot=plt.Circle((x[1]-0.12,y_mid),0.005,color=line_color,fill=True, linewidth=2)
  ax.add_patch(centre_circle)
  ax.add_patch(centre_spot)
  ax.add_patch(leftspot)
  ax.add_patch(rightspot)
  ## arcs
  left=Arc((x[0]+0.12,y_mid), width=0.22, height=0.18, angle=0.0, theta1=310, theta2=50, color=line_color, linewidth=2)
  right=Arc((x[1]-0.12,y_mid), width=0.22, height=0.18, angle=0.0, theta1=130, theta2=230, color=line_color, linewidth=2)
  ax.add_patch(left)
  ax.add_patch(right)
  ## corner arcs
  l1=Arc((x[0],y[0]), width=0.07, height=0.12, angle=0.0, theta1=0, theta2=90, color=line_color, linewidth=2)
  l2=Arc((x[0],y[1]), width=0.07, height=0.12, angle=0.0, theta1=270, theta2=360, color=line_color, linewidth=2)
  r1=Arc((x[1],y[0]), width=0.07, height=0.12, angle=0.0, theta1=90, theta2=180, color=line_color, linewidth=2)
  r2=Arc((x[1],y[1]), width=0.07, height=0.12, angle=0.0, theta1=180, theta2=270, color=line_color, linewidth=2)
  ax.add_patch(l1)
  ax.add_patch(l2)
  ax.add_patch(r1)
  ax.add_patch(r2)
  plt.axis("off")
  return ax


"""
# Shot Position Visualisation
"""
shots["X"] = shots["X"].multiply(x[1])
shots["Y"] = shots["Y"].multiply(y[1])




ax1 = pitch(x, y)

sns.scatterplot(x='X', y='Y', data=shots[shots["player"] == "Mohamed Salah"], size="xG", ax=ax1, hue="result", palette="Set2")


ax3 = pitch(x, y)

sns.kdeplot(x='X', y='Y', data=shots[shots["player"] == "Mohamed Salah"], shade= True, nlevels=10 , ax=ax3, pallete=(sns.color_palette("OrRd_r")), title="Kevin De Bruyne" )

"""
Removing penalties

"""
"""
# MODEL

"""
shots2.columns
final=shots2.loc[:,['minute', 'result', 'X', 'Y', 'xG', 'h_goals', 'a_goals'],]
X = final.drop(['result'], axis=1)
y = final['result']
print(X.shape)
print(y.shape)

X_train, X_test, y_train, y_test= train_test_split(X, y, test_size=0.4, random_state=5)
k_range = list(range(1,35))
scores = []
for k in k_range:
    knn = KNeighborsClassifier(n_neighbors=k)
    knn.fit(X_train, y_train)
    y_pred = knn.predict(X_test)
    scores.append(metrics.accuracy_score(y_test, y_pred))
    
plt.plot(k_range, scores)
plt.xlabel('Value of k for KNN')
plt.ylabel('Accuracy Score')
plt.title('Accuracy Scores for Values of k of k-Nearest-Neighbors')
plt.show()
model= LogisticRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(metrics.accuracy_score(y_test, y_pred))
##testing for knn=4
knn = KNeighborsClassifier(n_neighbors=12)
knn.fit(X,y)

knn.predict([[66, 0.885,	0.5,	0.7611688375473022, 1, 0]])