from easy_ko.main import *

import streamlit as st
import io
import pandas as pd
from pathlib import Path

HERE = Path(__file__).parent

# input_genes_file = "Candidate_genes.xlsx"
GTF_file = HERE/ "C_albicans_SC5314_version_A22-s07-m01-r105_features_A_and_B_allele_with_ntar.gtf"
assembly_file = HERE/ "Candida_albicans_SC5314_A22_current_default.fas"
PCR_components_file = HERE/ "CRISPR_parts.xlsx"
black_list_file = HERE/ "C_albicans_SC5314_A22_current_orf_genomic_all_v_all.csv"

st.set_page_config(
    page_title="EasY-KO"
)

st.title("EasY-KO")

"This program takes a list of target genes and generates the guide RNAs needed to remove these genes using Cas9. " \
"It also generates the primers needed to check whether the target gene is present (orf), " \
"check the length of the segment where the target gene used to be located (flank), and duplicate the integrated SAT + FLP sequence to be used as a repair template (SATFLP). " \
"The flank primers are also used to check whether the SAT + FLP sequence is present, having replaced the target gene. " \
"If a target gene has two alleles, it will generate components that target both."

def incomplete():
    st.session_state['complete'] = 0

# todo: add formatting info for upload
"### Upload target genes spreadsheet"
st.text("Upload an excel spreadsheet containing the systematic and standard names of the genes you want to target", 
        help="columns: Systematic Name | Gene Name")
with open(HERE/ "target_genes_example.xlsx", 'rb') as f:
    st.download_button("Download example target genes file", f, "target_genes_example.xlsx")
input_genes_file = st.file_uploader(label="Upload target genes spreadsheet: ", label_visibility="collapsed", type=['xlsx'], accept_multiple_files=False, on_change=incomplete)


with st.expander("More options"):

# move up
    "#### PCR components"
    st.text("The PCR components spreadsheet contains several useful nucleotide sequences. Two of these are attached to the guide RNA. " \
    "The spreadsheet contains the sequences of primers targeting the integrated SAT + FLP that pair with flank primers. " \
    "It also contains both of the primers targeting the edges of the SAT + FLP sequence used to duplicate the repair template.")
    with open(PCR_components_file, 'rb') as f:
        st.download_button("Download example PCR components file", f, "PCR_components_example.xlsx")
    PCR_components_file = st.file_uploader(label="Upload PCR components spreadsheet: ", label_visibility="collapsed", type=['xlsx'], accept_multiple_files=False, help="columns: Part Name | Part Sequence") or PCR_components_file

    "#### FASTA file"
    st.text("A FASTA file contains the full nucleotide sequences of each chromosome.")
    with open(assembly_file) as f:
        st.download_button("Download example FASTA file", f, "assembly_example.fas")
    assembly_file = st.file_uploader(label="Upload assembly file (fasta): ", label_visibility="collapsed", type=['fasta','fas'], accept_multiple_files=False) or assembly_file

    "#### GTF file"
    st.text("A GTF file contains information about the location and orientation of each gene in a genome. This program uses a GTF file to find sequences in the fasta file given the systematic name.")
    with open(GTF_file) as f:
        st.download_button("Download example GTF file", f, "GTF_example.gtf")
    GTF_file = st.file_uploader(label="Upload GTF file: ", label_visibility="collapsed", type=['gtf'], accept_multiple_files=False) or GTF_file # chooses new file unless it isn't uploaded
    
    "#### Blacklist file"
    st.text("The blacklist file is used to check the sequences of target genes against similar genes to make sure the guide RNA does not have any off-target effects. " \
    "The file contains all of the genes in the genome grouped into 'clusters,' with one row per cluster. The systematic names are separated by commas.")
    with open(black_list_file) as f:
        st.download_button("Download example blacklist file", f, "blacklist_example.csv")
    black_list_file = st.file_uploader(label="Upload blacklist file (csv): ", label_visibility="collapsed", type=['csv'], accept_multiple_files=False, help="columns: Cluster | Genes | Cluster Size") or black_list_file

if input_genes_file:
    # if not(st.session_state['complete']):
    if st.button("Generate components"):
        bar_label = st.empty()
        bar_label.write("""
        Generating components...
        """)
        bar = st.progress(0)
        st.session_state['df'], st.session_state['fig_data'] = main(input_genes_file,GTF_file,assembly_file, PCR_components_file, black_list_file, bar)

        output = io.BytesIO()
        with pd.ExcelWriter(output) as writer:
            st.session_state['df'].to_excel(writer, index=False)
        st.session_state['ss'] = output.getvalue()

        bar_label.empty()
        bar.empty()
        st.session_state['complete'] = 1

    if (st.session_state['complete']): # still have to make this check
        "## Download"
        st.download_button("Download CRISPR components spreadsheet", st.session_state['ss'], file_name='Candida_CRISPR_output.xlsx')

        "#### Output preview"
        st.dataframe(st.session_state['df'].head(10), hide_index=True)

        "## Visualization"
        gene = st.selectbox("Select a gene to visualize", list(st.session_state['fig_data'].keys()))
        fig = get_fig(gene, st.session_state['fig_data'][gene])
        st.write(fig)

#python3 -m streamlit run ./streamlit_app.py