import streamlit as st
import pandas as pd
import numpy as np
import datetime as dt
from dateutil.relativedelta import relativedelta 
import pandas as pd  
import plotly.express as px  # pip install plotly-express
import streamlit as st  
# from pyspark import SparkContext, SparkConf
# from pyspark.sql import SparkSession
# from pyspark.sql.types import StructType
# from pyspark.sql.types import StructField
# from pyspark.sql.types import StringType
import matplotlib.pyplot as plt
#import seaborn as sns
import altair as alt
from functions import *
from datetime import datetime, timedelta, date
import plotly.figure_factory as ff





# emojis: https://www.webfx.com/tools/emoji-cheat-sheet/
st.set_page_config(page_title="Media Planing",  layout="wide",page_icon="📊") #page_icon=":bar_chart:",
#st.set_page_config(page_title="Mapping Demo", page_icon="🌍")



st.title('"Media Planning"')


option=st.sidebar.selectbox(
    'some text here',
    ('first','one day', 'couple of days', "some specefic ad/ads"))

st.sidebar.write('You selected:', option)

df=pd.read_csv('pages/ads_historic.csv')
# st.dataframe(df)
if option=="first":
    pass

if option=="one day":
        
    
        d = st.sidebar.date_input(
    "Enter that day",
    datetime(2022, 10, 6))
      
        st.sidebar.markdown("""---""")
       
        
        one_day=df[df['day']==str(d)][["add_name" ,"day"]]
        # cercle
        one_day=one_day.groupby(pd.Grouper(key="add_name")).count().reset_index()
        one_day.rename(columns={'day': 'frequency'}, inplace=True)
        labels = one_day['add_name'].tolist()
 
        sizes = one_day['frequency'].tolist()
        #age = st.sidebar.slider('choose how many ads are the most accured?', 0, 10, 2)
        
        if len(sizes)==0: #one_day.shape == (0,0):
            pass
        else:
            age = st.sidebar.slider('choose how many ads are the most accured?', 0, 10, 2)
            kpi1, kpi2 = st.columns(2)
            with kpi1:
                st.write('the Ads that occur at least ',age,' times are :')
                st.json(get_most_ads(age,one_day))
            
            one_day=df[df['day']==str(d)][["add_name" ,"day"]]
            one_day=one_day.groupby(pd.Grouper(key="add_name")).count().reset_index()
            one_day.rename(columns={'day': 'frequency'}, inplace=True)
            
            with kpi2:
                kpi2.metric(
            label="Number of Ads ⏳",
            value=round(len(one_day['add_name'].tolist())))

            st.markdown("""---""")
            kp1, kp2 = st.columns(2)
            with kp1:
                st.write('The partition of the all Ads on ',d)
                fig1, ax1 = plt.subplots()
                ax1.pie(sizes,  labels=labels, autopct='%1.1f%%',
                        shadow=True, startangle=90)
                ax1.axis('equal')  

                st.pyplot(fig1)

            
            with kp2:
                chart = (
            alt.Chart(one_day)
            .mark_bar()
            .encode(
                x=alt.X("frequency", type="quantitative", title="frequency"),
                y=alt.Y("add_name", type="nominal", title="Ads name"),

            ).properties(title='Sales of consumer goods')
        )

                st.altair_chart(chart, use_container_width=True)
        
        

        
        


if option=="couple of days":

    
    kpi1, kpi2 = st.columns(2)


    start = st.sidebar.date_input(label='Start: ',
              value=datetime(year=2021, month=5, day=20, hour=16, minute=30),
              key='#start',
              help="The start date time",
                      on_change=lambda : None)

    end = st.sidebar.date_input(label='End: ',
                value=datetime(year=2021, month=5, day=30, hour=16, minute=30),
                key='#end',
                help="The end date time",
                        on_change=lambda : None)
    st.sidebar.write('Start: ', start, "End: ", end)
    st.sidebar.markdown("""---""")
    #age = st.sidebar.slider('choose how many ads are the most accured?', 0, 10, 2)

    df=pd.read_csv('pages/ads_historic.csv')
    df['day']=df['day'].apply(convert_date)
    df=df[(df['day']>=datetime.strptime(str(start), '%Y-%M-%d')) & (df['day']<=datetime.strptime(str(end), '%Y-%M-%d'))]

    df=pd.read_csv('pages/ads_historic.csv')
    df['day']=df['day'].apply(convert_date)
    df=df[(df['day']>=datetime.strptime(str(start), '%Y-%M-%d')) & (df['day']<=datetime.strptime(str(end), '%Y-%M-%d'))]
        
    one_day=df[["add_name" ,"day"]]
        # cercle
    one_day=one_day.groupby(pd.Grouper(key="add_name")).count().reset_index()
    labels = one_day['add_name'].tolist()
    one_day.rename(columns={'day': 'frequency'}, inplace=True)

    if len(labels)==0:
        pass
    else:
        age = st.sidebar.slider('choose how many ads are the most accured?', 0, 10, 2)
        with kpi1:
            st.write('the Ads that occur at least ',age)
            st.json(get_most_ads(age,one_day))
        with kpi2:
            kpi2.metric(
            label="Number of Ads ⏳",
            value=round(len(labels))
        
        )
        sizes = one_day['frequency'].tolist()
        st.markdown("""---""")
        kp1, kp2 = st.columns(2)
        
            
        with kp1:
            fig1, ax1 = plt.subplots()
            ax1.pie(sizes,  labels=labels, autopct='%1.1f%%',
                        shadow=True, startangle=90)
            ax1.axis('equal')  

            st.pyplot(fig1)

        with kp2:
            
            chart = (
            alt.Chart(one_day)
            .mark_bar()
            .encode(
                x=alt.X("frequency", type="quantitative", title="frequency"),
                y=alt.Y("add_name", type="nominal", title="Ads name")
                
            )
        )

            st.altair_chart(chart, use_container_width=True)
        
        df=pd.read_csv('pages/ads_historic.csv')
        result = pd.DataFrame()
        options2=df['add_name'].unique().tolist()
        for pub in options2:

            result=pd.concat([result,df[df['add_name']==pub]])
            
        gkk = result.groupby(['add_name','day']).size().reset_index()
        gkk.rename(columns={'day': 'frequency'}, inplace=True)
        gkk.rename(columns={0: 'value'}, inplace=True)
        chart = alt.Chart(gkk).mark_line().encode(
        x=alt.X('frequency:N'),
        y=alt.Y('value:Q'),
        color=alt.Color("add_name:N")
        ).properties(title="Hello World")
        st.altair_chart(chart, use_container_width=True)
    



if option=="some specefic ad/ads":
    option1 = st.sidebar.selectbox(
    'How many ads do you want to see',
    ('One', 'Many'))

    if option1=="One":
        df=pd.read_csv('pages/ads_historic.csv')
        ads_name=df['add_name'].unique().tolist()
        genre = st.sidebar.radio(
            "Select the Ad",
            ads_name)

        #df=pd.read_csv('pages/ads_historic.csv')
        ad_name=df[df['add_name']==genre]
        each_day=ad_name.groupby(pd.Grouper(key="day")).count().reset_index()[['day','add_name']]
        
        st.write('the max value is ',max_min(each_day)[0],' on ',max_min(each_day)[1],' and the min value is ',max_min(each_day)[2],' on ',max_min(each_day)[3])
        each_day.rename(columns={'add_name': 'frequency'}, inplace=True)
        st.line_chart(each_day, x="day", y="frequency", width=0, height=0, use_container_width=True)

    if option1=="Many":
        df=pd.read_csv('pages/ads_historic.csv')
        ads_name=df['add_name'].unique().tolist()
        st.sidebar.markdown("""---""")
        options2 = st.sidebar.multiselect('Choose the Ads',ads_name)

        result = pd.DataFrame()
        for pub in options2:
            result=pd.concat([result,df[df['add_name']==pub]])
        gkk=pd.DataFrame()
        gkk1=pd.DataFrame()
        #if result.shape != (0,0):
        if result.shape == (0,0):
            pass
        else:  
            gkk = result.groupby(['add_name','day']).size().reset_index()
            gkk.rename(columns={0: 'frequency'}, inplace=True)
            gkk1 = result.groupby(['add_name','day']).size().reset_index()
            gkk1.rename(columns={0: 'frequency'}, inplace=True)

            #st.dataframe(data=gkk,use_container_width=False)
            
            k1 ,k2=st.columns(2)
            
            with k1:
                gkk=gkk.groupby(pd.Grouper(key="add_name")).sum().reset_index()
                sizes=gkk['frequency'].tolist()
                labels=gkk['add_name'].tolist()
                #st.write('The partition of the all Ads on ',d)
                fig1, ax1 = plt.subplots()
                ax1.pie(sizes,  labels=labels, autopct='%1.1f%%',
                        shadow=True, startangle=90)
                ax1.axis('equal')  

                st.pyplot(fig1)
            with k2:
                gkk=gkk.groupby(pd.Grouper(key="add_name")).sum().reset_index()
                chart = (
                alt.Chart(gkk)
                .mark_bar()
                .encode(
                    x=alt.X("frequency", type="quantitative", title="frequency"),
                    y=alt.Y("add_name", type="nominal", title="Ads name"),

                ).properties(title='Sales of consumer goods')
            )

                st.altair_chart(chart, use_container_width=True)
            st.markdown("""---""")
            #st.dataframe(data=gkk1,use_container_width=False)
            chart = alt.Chart(gkk1).mark_line().encode(
            x=alt.X('day:N'),
            y=alt.Y('frequency:Q'),
            color=alt.Color("add_name:N")
            ).properties(title="Hello World")
            st.altair_chart(chart, use_container_width=True)



        # df=pd.read_csv('pages/ads_historic.csv')
        # ads_name=df['add_name'].unique().tolist()
        # options2 = st.sidebar.multiselect('Choose the Ads',ads_name)

        # result = pd.DataFrame()
        # df=pd.read_csv('pages/ads_historic.csv')
        # for pub in options2:
        #     #print(pub)
        #     result=pd.concat([result,df[df['add_name']==pub]])
        #     #result.append(df[df['add_name']==pub])

        # #st.dataframe(data=result,use_container_width=False)
        # gkk = result.groupby(['add_name','day']).size().reset_index()
        # gkk.rename(columns={'day': 'frequency'}, inplace=True)
        # #st.dataframe(data=gkk,use_container_width=False)

        # labels=gkk['add_name'].unique().tolist()
        # hist_data =[]
        # for la in labels:
        #     hist_data.append(np.array(gkk[gkk['add_name']==la][0].tolist()))
        # group_labels = labels
        # # Create distplot with custom bin_size
        # fig = ff.create_distplot(
        #         hist_data, group_labels)

        # # Plot!
        # st.plotly_chart(fig, use_container_width=True)

        
            
        

        

        

        




        
