import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
#import numpy as np
import datetime
from datetime import date
#import seaborn as sns

data = pd.read_excel(r'C:\Users\stani\Desktop\Webapp\st_zagora\income_data.xlsx') 
df_value = pd.DataFrame(data)

#df['data'] = pd.to_datetime(df['data']).dt.date
df_value['data'] = pd.to_datetime(df_value.data, format='%Y-%m-%d')
df_value['year'] = pd.DatetimeIndex(df_value['data']).year
#print(df['year'].unique())

year_float=df_value['year'].unique()
df_value['quarter'] = df_value['data'].dt.quarter
quarter= df_value['quarter']
year=list(map(str,year_float))

st.set_page_config(layout="wide")



#st.markdown("## Income and Expenses in Dairy Farm")   ## Main Title
st.markdown("<h2 style='text-align: center; color: black;'>Income and Expenses in Dairy Farm</h2>", unsafe_allow_html=True)

#df['quarter'] = df['data'].dt.to_period('Q')

#st.write(df['quarter'])



################# Scatter Chart Logic #################

st.sidebar.markdown("### Chooice year :")
axis_year = st.sidebar.multiselect(label ="Chooice year",
            options=year,
            default=['2019', '2020', '2021'])
choice_value = list(map(int, axis_year))


################# Histogram Logic ########################

st.sidebar.markdown("### Chooice quater :")
           
axis_quater = st.sidebar.multiselect(
    'Chooice quarter',
    ['Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'],
           default= ['Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'])
i = 0
while i < len(axis_quater):
 
    if axis_quater[i] == 'Quarter 1':
        axis_quater[i] = 1
 
    # replace pant with ishan
    if axis_quater[i] == 'Quarter 2':
        axis_quater[i] = 2
        
    if axis_quater[i] == 'Quarter 3':
        axis_quater[i] = 3
 
    if axis_quater[i] == 'Quarter 4':
        axis_quater[i] = 4
 
    i += 1
choice_quater=axis_quater

df1_value=df_value[df_value['year'].isin(choice_value) & df_value['quarter'].isin(choice_quater)]


#import streamlit as st
#import matplotlib.pyplot as plt

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
#labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
#sizes = [15, 30, 45, 10]
#explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')



#df['data'] = pd.to_datetime(df['data']).dt.date
#df['year'] = pd.DatetimeIndex(df['data']).year
#datas = df['data'].year

#print(df['year'])
#

#for ele in df['year']:
 
    # checking for date in range
 #   if ele == 2021:
        
 # Data to plot
labels_income = 'Income milk', 'Income animal', 'Grand', 'Income calves' 
        #sizes = [215, 130, 245, 210]
        #colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
        #explode = (0, 0, 0, 0)  # explode 1st slice
income_milk = df1_value['income_milk'].sum()
income_animal = df1_value['income_animal'].sum()
income_calves = df1_value['income_calves'].sum()
income_grand= df1_value['grand'].sum()
        
        #total_income = (df['income_milk'], df['income_animal'],df['income_calves'], df['grand']).sum()
total_income = sum([income_milk, income_animal, income_calves, income_grand])
percent_milk = income_milk/total_income*100
percent_animal = income_animal/total_income*100
percent_calves = income_calves/total_income*100
percent_grand = income_grand/ total_income*100 
sizes_income=[percent_milk, percent_animal, percent_grand, percent_calves] 


medicine = df1_value['medicine'].sum()
energy = df1_value['energy'].sum()
insurance = df1_value['insurance'].sum()
salaries_insurance = df1_value['salaries_insurance'].sum()
creditss = df1_value['creditss'].sum()
interest_loans = df1_value['interest_loans'].sum()
leasing_contracts = df1_value['leasing_contracts'].sum()
fuel = df1_value['fuel'].sum()
repair = df1_value['repair'].sum()
forage = df1_value['forage'].sum()
seminal_fluid = df1_value['seminal_fluid'].sum()
ear_tags = df1_value['ear_tags'].sum()
others = df1_value['others'].sum()
total_expenses = df1_value['total_expenses'].sum()

percent_medicine = medicine / total_expenses*100
percent_energy = energy / total_expenses*100
percent_insurance = insurance / total_expenses*100
percent_salaries_insurance = salaries_insurance / total_expenses*100
percent_creditss = creditss / total_expenses*100
percent_interest_loans = interest_loans / total_expenses*100
percent_leasing_contracts = leasing_contracts / total_expenses*100
percent_fuel = fuel / total_expenses*100
percent_repair = repair / total_expenses*100
percent_forage = forage / total_expenses*100
percent_seminal_fluid = seminal_fluid / total_expenses*100
percent_ear_tags = ear_tags / total_expenses*100
percent_others = others / total_expenses*100

sizes_expenses = [percent_medicine, percent_energy, percent_insurance, percent_salaries_insurance,  percent_creditss, percent_interest_loans, percent_leasing_contracts, percent_fuel, percent_repair, percent_forage, percent_seminal_fluid, percent_ear_tags, percent_others]
labels_expenses = 'Medicine', 'Electro energy', 'Insurance', 'Salaries insurance', 'Credit', 'Interest_loan', 'Leasing contracts', 'Fuel', 'Repeir', 'Forage', 'Seminal fuid', 'Ear tags', 'Others'  

container1 = st.container()
col1, col2 = st.columns(2)
container2 = st.container()
col3, col4 = st.columns(2)
with container1:

    with col1:
        pie_fig1 = plt.figure(figsize=(6,4))
        pie_ax1 = pie_fig1.add_subplot(111)
        pie_ax1.pie(sizes_income, labels = labels_income, autopct='%1.1f%%')
        #pie_ax1.legend(loc='lower right')
        plt.show()
        plt.title('Different income streams')
        st.pyplot(pie_fig1)
       
    with col2:
        pie_fig2 = plt.figure(figsize=(6,4))
        pie_ax2 = pie_fig2.add_subplot(111)
        pie_ax2.pie(sizes_expenses, labels = labels_expenses, autopct='%1.1f%%')
        #pie_ax2.legend(loc='lower right')
        plt.show()
        plt.title('Different expenses streams')
        st.pyplot(pie_fig2)
      
with container2:
        with col3:
         line_fig3 = plt.figure(figsize=(6,4))
         line_ax3 = line_fig3.add_subplot(111)
         #line_ax3.plot(df1_value['data'], 
         line_ax3.plot(df1_value['data'], df1_value['income_milk'], linestyle='solid', color='r', label='Income milk')
         line_ax3.plot(df1_value['data'], df1_value['income_animal'], linestyle='dotted', color='orange', label='Income animal')
         line_ax3.plot(df1_value['data'], df1_value['income_calves'], linestyle='dashed', color='g', label='Income calves')
         line_ax3.plot(df1_value['data'], df1_value['grand'], linestyle='dashdot', color='b', label='Grand')
         line_ax3.legend()
         plt.show()
         plt.title('Income flow')
         st.pyplot(line_fig3)
         
        with col4:
         line_fig4 = plt.figure(figsize=(6,4))
         line_ax4 = line_fig4.add_subplot(111)
         #line_ax3.plot(df1_value['data'], 
         line_ax4.plot(df1_value['data'], df1_value['medicine'])
         line_ax4.plot(df1_value['data'], df1_value['energy'])
         line_ax4.plot(df1_value['data'], df1_value['insurance'])
         line_ax4.plot(df1_value['data'], df1_value['creditss'])
         line_ax4.plot(df1_value['data'], df1_value['interest_loans'])
         line_ax4.plot(df1_value['data'], df1_value['leasing_contracts'])
         line_ax4.plot(df1_value['data'], df1_value['fuel'])
         line_ax4.plot(df1_value['data'], df1_value['repair'])
         line_ax4.plot(df1_value['data'], df1_value['forage'])
         line_ax4.plot(df1_value['data'], df1_value['seminal_fluid'])
         line_ax4.plot(df1_value['data'], df1_value['ear_tags'])
         line_ax4.plot(df1_value['data'], df1_value['others'])
         line_ax4.legend()
         plt.show()
         plt.title('Expeses flow')
         st.pyplot(line_fig4)
    
#y1list = df["production_cost"].tolist()
#plt.savefig("output1.jpg")
         
        # Plot
#fig1, ax1 = plt.subplots()
        #ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
         #   shadow=True, startangle=90)
#pie_ax1.pie(sizes_income, labels = labels, autopct='%1.1f%%')
#pie_ax1.legend(loc='lower right')
#plt.show() 
#plt.title('Different income streams')
        #ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
#st.pyplot(pie_fig11)
    #st.pyplot(fig1)



    #plt.pie(sizes, explode=explode, labels=labels, colors=colors,
     #   autopct='%1.1f%%', shadow=True, startangle=90)
      
    #plt.axis('equal')
    #plt.show()
#st.pyplot(fig1)