# -*- coding: utf-8 -*-
"""
Spyder Editor

This is a temporary script file.
"""

import streamlit as st
import pandas as pd
import numpy as np
import seaborn as sns
import plotly.express as px
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression,Lasso,Ridge
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
st.title('Dream House')
# go to anaconda prompt and use cd <paste path> to change base folder path
# streamlit run filename.py in anaconda
st.text('Find you dream homes here')
# SAVE HERE and rerun in website
df=pd.read_csv('kc_house_data.csv')
#st.image('Hand.jpg')
st.video('https://www.youtube.com/watch?v=rUWxSEwctFU')

#####################################
######### SLIDER ####################
#####################################

sldr=st.slider("Slider",min_value=0,max_value=100,step=1)
st.text("selected range " + str(sldr))

sldr_df=st.slider("Slider from dataframe",min_value=int(df['price'].min()),max_value=int(df['price'].max()),step=1)
test_price_set=st.slider("Price Range",min_value=int(df['price'].min()),max_value=int(df['price'].max()),step=50,value=int(df['price'].max()))

#minvalue of price will be taken as minmum value of dataframe already read from price column
st.text("Range from price column "+str(test_price_set))

fig=px.scatter_mapbox(df,lat='lat',lon='long',color='sqft_living',size='price')
fig.update_layout(mapbox_style='open-street-map')
st.plotly_chart(fig)

## here settinf the price limit by usding df.loc[df[price]<price_set]
price_set=st.slider("Price Range 1",min_value=int(df['price'].min()),max_value=int(df['price'].max()),step=50,value=int(df['price'].max()))

fig=px.scatter_mapbox(df.loc[df['price']<price_set],lat='lat',lon='long',color='sqft_living',size='price')
fig.update_layout(mapbox_style='open-street-map')
st.plotly_chart(fig)

#######################################################################
##########  MACHINE LEARNING ##########################################
######################################################################


st.title('Price Predictor')
#select type of method
sel_box_var=st.selectbox("Select Method",['Linear','Ridge','Lasso'],index=0)
#select filter/variables that is necessary
multi_var=st.multiselect("Select Additional Variables for Accuracy=",['sqft_living','sqft_lot','sqft_basement'])
#create new dictionary to keep the filter(multi_var value)
df_new=[]
df_new=df[multi_var]
if sel_box_var=='Linear':
    df_new['bedrooms']=df['bedrooms']
    df_new['bathrooms']=df['bathrooms']
    X=df_new
    Y=df['price']
    model=LinearRegression()
    X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2)
    reg=model.fit(X_train,Y_train)  
    Y_pred = reg.predict(X_test)
    st.text("Intercept="+str(reg.intercept_))
    st.text("Coefficient="+str(reg.coef_))
elif sel_box_var=='Lasso':
    df_new['bedrooms']=df['bedrooms']
    df_new['bathrooms']=df['bathrooms']
    X=df_new
    Y=df['price']
    model=Lasso()
    X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2)
    reg=model.fit(X_train,Y_train)  
    Y_pred = reg.predict(X_test)
    st.text("Intercept="+str(reg.intercept_))
    st.text("Coefficient="+str(reg.coef_))
    st.text("R^2="+str(r2_score(Y_test,Y_pred)))
else:
    df_new['bedrooms']=df['bedrooms']
    df_new['bathrooms']=df['bathrooms']
    X=df_new
    Y=df['price']
    model=Ridge()
    X_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.2)
    reg=model.fit(X_train,Y_train)  
    Y_pred = reg.predict(X_test)
    st.text("Intercept="+str(reg.intercept_))
    st.text("Coefficient="+str(reg.coef_))
    st.text("R^2="+str(r2_score(Y_test,Y_pred))) 
## IF warning comes because package is old use following code
st.set_option('deprecation.showPyplotGlobalUse',False)
# Plotting regression
sns.regplot(Y_test,Y_pred)
st.pyplot()
#regression will be used to predict price based on user input
count=0
pred_val=0
for i in df_new.keys():   #for every item in df_new
    try:                  # Try the value entered by user
        val=st.text_input("Enter no./val of"+i)
        pred_val=pred_val+float(val)*reg.coef_[count]
        count=count+1     #move to next item in df.new
    except:               #if the value entered is not correct, ignore error and move
        #pass
        st.text("Please Enter correct value")

st.text('Predicted Prices are:'+str(pred_val+reg.intercept_)) #ax+b 

#######################################################################################
####################### APPLICATION DETAILS ###########################################
#######################################################################################

st.header("Application Details")
img=st.file_uploader("Upload Application")

######## FORM ################# 
st.text("Details for the representative to contact you")
st.text("Enter your address")
address=st.text_area("Your address Here")
# Add this to dataframe using append

date=st.date_input("Enter a date")
time=st.time_input("Enter the time")
if st.checkbox("I confirm the date and time",value=False):
    st.write("Thanks for confirming")
st.number_input("Rate our site",min_value=1.0,max_value=10.0,step=1.0)
