import streamlit as st
import pandas as pd
from datetime import datetime
from streamlit_ext import download_button as down_btn


def generate_perforations(df,plug_df):
    content = "UNITS METRIC\n\n"

    # Iterate through unique well names
    for well_name in df['well'].unique():
        content += f'WELLNAME "{well_name}"\n'

        # Filter the dataframe for the current well
        well_df = df[df['well'] == well_name]

        # Iterate through rows of the filtered dataframe
        for index, row in well_df.iterrows():
            if row['type'] == 'p':
                date = row['date'].strftime('%d/%m/%Y')
                top = row['top']
                btm = row['btm']
                # Write the perforation line to the content
                content += f'{date} perforation {top} {btm} 0.1905 0 0 0\n'

            if row['type'] == 's':
                date = row['date'].strftime('%d/%m/%Y')
                top = row['top']
                btm = row['btm']
                # Write the shut-in line to the content
                content += f'{date} squeeze {top} {btm}\n'

        # Filter the plug dataframe for the current well
        plug_well_df = plug_df[plug_df['well'] == well_name]

        # Iterate through rows of the filtered plug dataframe
        for index, plug_row in plug_well_df.iterrows():
            date = plug_row['date'].strftime('%d/%m/%Y')
            depth = plug_row['depth']

            # Filter the well dataframe based on the plug depth
            filtered_well_df = well_df[(well_df['top'] >= depth) | (well_df['btm'] >= depth)]

            # Iterate through rows of the filtered well dataframe
            for _, filtered_row in filtered_well_df.iterrows():
                top = filtered_row['top']
                btm = filtered_row['btm']
                if depth > top and depth < btm:
                    # Write the plug line to the content
                    content += f'{date} squeeze {depth} {btm}\n'
                else :# Write the squeeze line to the content
                    content += f'{date} squeeze {top} {btm}\n'

        content += "\n"  # Add a newline between well sections

    return content

def generate_tubing(df,tubing=False):
    content = "UNITS METRIC\n\n"

    # Iterate through unique well names
    for well_name in df['well'].unique():
        content += f'DATE {df["date"].min().strftime("%Y-%m-%d")}\n'

        # Filter the dataframe for the current well
        well_df = df[df['well'] == well_name]

        # Get the deepest perforation depth for the current well
        deepest_depth = well_df['btm'].max() + 20
        shallowest_depth = well_df['top'].min() - 20

        # Write the casing information to the content
        content += f'CASING "{well_name}" "Casing 1"\n'
        content += '0 "C-API-6.625/J-55/20.00"\n'
        content += f'{deepest_depth}\n\n'

        if tubing:
            # Write the tubing information to the content
            content += f'TUBING "Tubing 1" "{well_name}" "{well_name}"\n'
            content += '0 "T-API-5.000/J-55/11.50"\n'
            content += f'{shallowest_depth}\n'

            # Write the packer information to the content
            content += f'PACKER "Packer 1" "{well_name}" {shallowest_depth - 30} "PK_ADD_ON1"\n\n'

    return content




def main():
    #change the page title
    st.set_page_config(page_title="Petrel Perforation and Tubing File Generator",layout="wide")
    #change the page icon
    st.markdown(""" <style>
    #MainMenu {visibility: hidden;}
    footer {visibility: hidden;}
    </style> """, unsafe_allow_html=True)
    

    st.title("Petrel Perforation and Tubing File Generator")

    # Upload Excel file
    uploaded_file = st.sidebar.file_uploader("Upload Perforation Excel file", type=["xlsx", "xls"])
    #check box for tubing
    tubing = st.sidebar.checkbox("Tubing",value=False)

    if uploaded_file is not None:
        # Read the Excel file
        df = pd.read_excel(uploaded_file,sheet_name='perforation')
        plug_df = pd.read_excel(uploaded_file,sheet_name='plugs')

        # Create button to begin the process
    if st.sidebar.button("Generate"):
        # Prevent page refresh using a callback
        st.session_state.generate_clicked = True  # Flag for callback

    # Use a callback to execute actions only when the button is clicked
    if st.session_state.get("generate_clicked", False):
        # Generate content for perforations.ev and tubing.tub
        perforations_content = generate_perforations(df,plug_df)
        tubing_content = generate_tubing(df, tubing=tubing)

        # Display perforations.ev content
        st.subheader("Click the button below to download perforations.ev and tubing.tub")
        # Create buttons to download files
        down_btn(
            label="Download perforations.ev",
            data=perforations_content,
            file_name="perforations.ev"
        )

        down_btn(
            label="Download tubing.tub",
            data=tubing_content,
            file_name="tubing.tub"
        )

        # Reset the flag after execution
        st.session_state.generate_clicked = False



if __name__ == "__main__":
    main()