# -*- coding: utf-8 -*-
"""
Created on Sun Mar 28 22:55:18 2021

@author: Ibrahim
"""

import streamlit as st
import SessionState  # Assuming SessionState.py lives on this folder
import base64
import sqlite3
from PIL import Image
import time
import sqlite3
import pandas as pd
import time, os, re
import streamlit as st
import streamlit.components.v1 as components
import numpy as np
from random import shuffle
from random import sample


conn = sqlite3.connect("data.db")
c= conn.cursor()

def create_usertable():
    c.execute('CREATE TABLE IF NOT EXISTS userstable(username TEXT, age TEXT, password TEXT)')

def add_userdata(username,age,password):
    c.execute('INSERT INTO userstable(username,age,password) VALUES (?,?,?)',(username,age, password))    
    conn.commit()
    
    
def login_user(username,age,password):
    c.execute('SELECT * FROM userstable WHERE username =? AND age =? AND password =?',(username,age, password))    
    data = c.fetchall()
    return data


def view_all_users():
    c.execute('SELECT * FROM userstable')
    data = c.fetchall()
    return data






def main():
        
    images_list = []
    for i in os.listdir("images"):
        images_list.append(i)
        
      
    session = SessionState.get(state = 0, run_id=0,reward = 0, button=0)
    
    
    
          
    file_name = "style_home.css"
    def local_css(file_name):
        with open(file_name) as f:
            st.markdown(f'<style>{f.read()}</style>', unsafe_allow_html=True)
    
    def remote_css(url):
        st.markdown(f'<link href="{url}" rel="stylesheet">', unsafe_allow_html=True)    
    
    def icon(icon_name):
        st.markdown(f'<i class="material-icons">{icon_name}</i>', unsafe_allow_html=True)
    
    local_css("style_home.css")
    
    
    
    # file_ = open("turing_game.png", "rb")
    # contents = file_.read()
    # data_url = base64.b64encode(contents).decode("utf-8")
    # file_.close()
    
    # st.markdown(
    #     f'<img src="data:image/gif;base64,{data_url}" alt="Logo" class="center" style="width:300*2.9 px;height:300px;">',
    #     unsafe_allow_html=True,
    # )
    
    # st.write('<style>div.Widget.row-widget.stRadio > div{flex-direction:row;}</style>', unsafe_allow_html=True)
    
    image = Image.open("turing_game.png")
    
    st.image(image, use_column_width="auto")
    
    st.markdown("<h1 style='text-align: center; color: black;'>CAN YOU TELL WHAT IS REAL?</h1>", unsafe_allow_html=True)
    
    title_1 = st.empty()
    #title_1.markdown("<h1 style='text-align: center; color: black;'>Select your age, gender, and yes to play!</h1>", unsafe_allow_html=True)
    title_1.text("Select your age, gender, and yes to play!")
    
    
    
    ############## to hide "made by streamlit footer "
    hide_streamlit_style = """
                <style>
                #MainMenu {visibility: hidden;}
                footer {visibility: hidden;}
                </style>
                """
    st.markdown(hide_streamlit_style, unsafe_allow_html=True)
    
    
        
    st.sidebar.title("CAN YOU TELL WHAT IS REAL?")
    st.sidebar.header("How to play:")
    st.sidebar.markdown("1. Every image will last only for one second twice")
    st.sidebar.markdown("2. Define whether a give image is real or fake")
    st.sidebar.markdown("3. There are 50 images in total")    
    st.sidebar.markdown("4. At the end, you will recieve a score")
    st.sidebar.markdown("5. Stay focus and try to achieve 100% score")
    st.sidebar.markdown("6. Select your age, gender, and play")
    
    
    age_menu = st.empty()
    gender_menu = st.empty()
    play_menu =st.empty()
    
    
    age= age_menu.selectbox("Age group", ["None","18-25", "26-30", "31-39", "40-49", "50-59", "60 or above"])
    gender= gender_menu.selectbox("Gender", ["None", "Male", "Female", "Don't want to share"])
    
    play = play_menu.selectbox("Play? ", ["No", "yes"])
    
    st.sidebar.header("What is it?")
    st.sidebar.markdown("This is a social experiment inspired by the Turing test. We ask participants to define whether a given image is a real or fake street-level image. Images appear only for one second twice to make a judgement and in the end, you will get a score of what you have achieved. The average reaction time for humans is 0.25 seconds to a visual stimulus (4 images per second). The synthesis images are generated by a GAN model created by Mohamed R. Ibrahim (Currently under review). The purpose of this game is to validate the model. Nevertheless, it aims to show quantitive evidence of how mixed reality can alter our ground truth. The results of this experiment might be used for AI perception research.")
    
    
    # st.sidebar.header("Previous scores:")
    
    # data_file = st.sidebar.button("Data",key=23232)
    # if data_file:
    #     user_result = view_all_users()
    #     clean_db = pd.DataFrame(user_result,columns=["gender","age","score"])
    #     st.sidebar.dataframe(clean_db)
    
    st.sidebar.markdown("The tool is created by Mohamed R. Ibrahim as an open-source software")
    st.sidebar.markdown("PhD researcher, University College London (UCL), London, UK")
    st.sidebar.markdown("For more info, contact: mohamed.ibrahim.17 [at] ucl.ac.uk")

    
    st.sidebar.write("Check out our website: [URBAN-i](https://www.urban-i.ai)")
    st.sidebar.markdown("© 2020  All Rights Reserved. URBAN-i is a registered UK trademark with number: UK00003461106")
    
    
    
    df1 = pd.DataFrame()



    
    if (age != "None" and gender != "None"):
        
        
        if play =="yes":
    
            # if session.run_id ==0:
            #     age_menu.empty()
            #     gender_menu.empty()
            #     play_menu.empty()
                
            
    
            
            # score = session.reward
            # answer =int()
            # gt = int()
            
            if session.state ==0:
                
    
                title_1.markdown("<h1 style='text-align: center; color: black;'>Play in: 3</h1>", unsafe_allow_html=True)
                time.sleep(1)
                title_1.markdown("<h1 style='text-align: center; color: black;'>Play in: 2</h1>", unsafe_allow_html=True)
                time.sleep(1)
                title_1.markdown("<h1 style='text-align: center; color: black;'>Play in: 1</h1>", unsafe_allow_html=True)
                time.sleep(0.1)
                title_1.empty()
        
        
            title_1.empty()
            image_counter = st.empty()
            image_place =st.empty()
        
            button_1 =st.empty()
            button_2 =st.empty()
            score = session.reward
            answer =int()
            gt = int()
        
            if  session.run_id < len(images_list):
                print(session.state)
                image = Image.open("images/"+images_list[session.run_id])
                image_place.image(image, width=500)
                time.sleep(1)
        
                counter = title_1.title("Image count: "+ str(session.run_id+1)+"/"+str(len(images_list)))
                ground_truth = images_list[session.run_id].split(".",2)[0][5:9]
                match_fake = re.search(r'\bfake\b',ground_truth)
                match_real = re.search(r'\breal\b',ground_truth)
                if match_fake:
                    gt = 0
        
                if match_real:
                    gt = 1
    
                
                #image_place.empty()
                #image_counter.empty()
                
                image_place.title("Is it real?")
                
                if button_1.button("Yes", key=session.button):
                    
                   #session.run_id += 1
                   answer = 1
                   
                   if answer == gt:
                       session.reward += 1
                       score = session.reward
                   print(session.state, session.run_id, age,gender,answer,gt,score, str(images_list[session.run_id]))
                   
                   session.run_id += 1
                   session.button += 1
    
                       
                           
                if button_2.button("No", key=session.button):
                   #session.run_id += 1
                   answer = 0
                   if answer == gt:
                       session.reward += 1
                       score = session.reward
                   print(session.state,session.run_id, age,gender,answer,gt,score, str(images_list[session.run_id]))
                   session.run_id += 1
                   session.button += 1
                   
                session.state +=1

    
    
                       
    
                   
                #session.run_id += 1
               # print("debug",session.run_id, age,gender,answer,gt,score, str(images_list[session.run_id]))
            
    
        
            else: 
                #st.balloons()
                achievement = int(score/len(images_list)*100)
                age_menu.empty()
                gender_menu.empty()
                play_menu.empty()
                if achievement > 75:
                    st.balloons()
                    
                
                image_place.title("Your score is: {}%".format(achievement))
                
                create_usertable()
                add_userdata(str(gender), str(age),str(achievement))
                
                images_list = sample(images_list, len(images_list))
        
                session.run_id =0
                session.reward=0
                score = 0
                
                if st.button("Play again?"):
                    session.run_id =0
                    session.reward=0
                    score = 0
                    
                    
            
if __name__ == "__main__":
    main()        
    





