import os
from PIL import Image
import secrets
import csv
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
import numpy as np
import random as rd
import smtplib


areastatpath = 'images/areastat/'  #respective path of the images 
fakepath = 'images/fake/'          #respective path of the images
googlepath = 'images/google/'      #respective path of the images
faqpath = 'images/faq/'            #respective path of the images

areastat_images = [f for f in os.listdir(areastatpath) if os.path.splitext(f)[-1] == '.png']
fake_images = [f for f in os.listdir(fakepath) if os.path.splitext(f)[-1] == '.png']
faq_images = [f for f in os.listdir(faqpath) if os.path.splitext(f)[-1] == '.png']
google_images = [f for f in os.listdir(googlepath) if os.path.splitext(f)[-1] == '.png']

php_code = ''
with open('abc.php', 'r') as f:
  php_code = str(f.read())

fake_queries = []
with open("fake.txt") as file_in:
    for line in file_in:
      fake_queries.append(line.strip())

google_queries = []
with open("google.txt") as file_in:
    for line in file_in:
      google_queries.append(line.strip())

areastat_queries = []
with open("areastat.txt") as file_in:
    for line in file_in:
      areastat_queries.append(line.strip())

faq_queries = []
with open("faq.txt") as file_in:
    for line in file_in:
      faq_queries.append(line.strip())

google_subheadings = []
with open("google_subheading.txt") as file_in:
    for line in file_in:
      google_subheadings.append(line.strip())

faq_subheadings = []
with open("faq_subheading.txt") as file_in:
    for line in file_in:
      faq_subheadings.append(line.strip())

fake_subheadings = []
with open("fake_subheading.txt") as file_in:
    for line in file_in:
      fake_subheadings.append(line.strip())

mapping = {}
email = []

with open('emails.csv') as f:
    csv_reader = csv.reader(f)
    for row in csv_reader:
        email.append(row[0])

users = [secrets.token_hex(16) for i in range(len(email))]

server_address = 'https://swaprava.cse.iitk.ac.in/'
with open('emails.csv') as f:
    csv_reader = csv.reader(f)
    i = 0
    for row in csv_reader:
        email_id = row[0]
        mapping[users[i]] = email_id
        i = i+1


areastat_temp = '''<div class="form-group">
      <label style="font-size:130%;" style="font-family:courier;">QUERY: {}</label><br><br>
      &emsp;&emsp;&emsp;&ensp;<label>Response in Chatbot 1</label>&emsp;&emsp;&ensp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
      <label>Response in Chatbot 2</label>
      <img align="left" src="images/areastat/{}" alt="Satyanweshi Logo 1" style="width:250px;height:600px;">
      <img align="right" src="images/areastat/{}" alt="Satyanweshi Logo 2" style="width:250px;height:600px;"><br>'''

common_temp = '''</div>
     <br><div class = "form-group" id = "leftbox"><br>
       &emsp;&emsp;&emsp;&ensp;<input type="radio" id="star1" name="rating{}" value="1" />&emsp;
       <input type="radio" id="star2" name="rating{}" value="2" />&emsp;
       <input type="radio" id="star3" name="rating{}" value="3" />&emsp;
       <input type="radio" id="star4" name="rating{}" value="4" />&emsp;
       <input type="radio" id="star5" name="rating{}" value="5" /><br>
       &ensp;&emsp;&emsp;&ensp;&ensp;
       <label for="star1" title="Very Poor">1</label>&emsp;&ensp;
       <label for="star2" title="Poor">2</label>&emsp;&ensp;
       <label for="star3" title="Good">3</label>&ensp;&emsp;
       <label for="star4" title="Very Good">4</label>&emsp;&ensp;
       <label for="star5" title="Outstanding">5</label><br>
       &emsp;&emsp;&emsp;&emsp;&emsp;<label>Select the rating</label><br>
     </div><br>
     <div class = "form-group" id = "rightbox"><br>
       &emsp;&emsp;&emsp;&ensp;<input type="radio" id="star1" name="rating{}" value="1" />&emsp;
       <input type="radio" id="star2" name="rating{}" value="2" />&emsp;
       <input type="radio" id="star3" name="rating{}" value="3" />&emsp;
       <input type="radio" id="star4" name="rating{}" value="4" />&emsp;
       <input type="radio" id="star5" name="rating{}" value="5" /><br>
       &ensp;&emsp;&emsp;&ensp;&ensp;
       <label for="star1" title="Very Poor">1</label>&emsp;&ensp;
       <label for="star2" title="Poor">2</label>&emsp;&ensp;
       <label for="star3" title="Good">3</label>&ensp;&emsp;
       <label for="star4" title="Very Good">4</label>&emsp;&ensp;
       <label for="star5" title="Outstanding">5</label><br>
       &emsp;&emsp;&emsp;&emsp;&emsp;<label>Select the rating</label><br>
      </div><br>'''

fake_temp = '''<div class="form-group">
      <label style="font-size:130%;" style="font-family:courier;">QUERY: {}</label><br>
      <label style="font-size:130%;color:SlateBlue;">HINT: {}</label><br><br>
      &emsp;&emsp;&emsp;&ensp;<label>Response in Chatbot 1</label>&emsp;&emsp;&ensp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
      <label>Response in Chatbot 2</label>
      <img align="left" src="images/fake/{}" alt="Satyanweshi Logo 1" style="width:250px;height:800px;">
      <img align="right" src="images/fake/{}" alt="Satyanweshi Logo 2" style="width:250px;height:800px;"><br>'''

google_temp = '''<div class="form-group">
      <label style="font-size:130%;" style="font-family:courier;">QUERY: {}</label><br>
      <label style="font-size:130%;color:SlateBlue;">HINT: {}</label><br><br>
      &emsp;&emsp;&emsp;&ensp;<label>Response in Chatbot 1</label>&emsp;&emsp;&ensp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
      <label>Response in Chatbot 2</label>
      <img align="left" src="images/google/{}" alt="Satyanweshi Logo 1" style="width:250px;height:800px;">
      <img align="right" src="images/google/{}" alt="Satyanweshi Logo 2" style="width:250px;height:800px;"><br>'''

faq_temp = '''<div class="form-group">
      <label style="font-size:130%;" style="font-family:courier;">QUERY: {}</label><br>
      <label style="font-size:130%;color:SlateBlue;">HINT: {}</label><br><br>
      &emsp;&emsp;&emsp;&ensp;<label>Response in Chatbot 1</label>&emsp;&emsp;&ensp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;
      <label>Response in Chatbot 2</label>
      <img align="left" src="images/faq/{}" alt="Satyanweshi Logo 1" style="width:250px;height:600px;">
      <img align="right" src="images/faq/{}" alt="Satyanweshi Logo 2" style="width:250px;height:600px;"><br>'''

end = '''<div class="form-group" align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Submit" />
     </div>
    </form>
   </div>
  </div>
 </body>
</html>'''


var = '''$user_id = '{}';
  $query1_id = '{}';
  $query2_id = '{}';
  $query3_id = '{}';
  $query4_id = '{}';
  $query5_id = '{}';
  $query6_id = '{}';
  $query7_id = '{}';
  $query8_id = '{}';
  $query9_id = '{}';
  $query10_id = '{}';
  '''

A = '''
  $form_data = array(
   'timestamp' => $timestamp,
   'user_id'  => $user_id,
   'queryid1' => $query1_id,
   'rating1'  => $rating1,
   'rating2'  => $rating2,
   'queryid2' => $query2_id,
   'rating3' => $rating3,
   'rating4' => $rating4,
   'queryid3' => $query3_id,
   'rating5' => $rating5,
   'rating6' => $rating6,
   'queryid4' => $query4_id,
   'rating7' => $rating7,
   'rating8' => $rating8,
   'queryid5' => $query5_id,
   'rating9' => $rating9,
   'rating10' => $rating10,
   'queryid6' => $query6_id,
   'rating11'  => $rating11,
   'rating12'  => $rating12,
   'queryid7' => $query7_id,
   'rating13' => $rating13,
   'rating14' => $rating14,
   'queryid8' => $query8_id,
   'rating15' => $rating15,
   'rating16' => $rating16,
   'queryid9' => $query9_id,
   'rating17' => $rating17,
   'rating18' => $rating18,
   'queryid10' => $query10_id,
   'rating19' => $rating19,
   'rating20' => $rating20
  );
  fputcsv($file_open, $form_data);
  $error = '<label class="text-success">Thank you for filling the form</label>';
  $timestamp = '';
  $rating1 = '';
  $rating2 = '';
  $rating3 = '';
  $rating4 = '';
  $rating5 = '';
  $rating6 = '';
  $rating7 = '';
  $rating8 = '';
  $rating9 = '';
  $rating10 = '';
  $rating11 = '';
  $rating12 = '';
  $rating13 = '';
  $rating14 = '';
  $rating15 = '';
  $rating16 = '';
  $rating17 = '';
  $rating18 = '';
  $rating19 = '';
  $rating20 = '';
  $user_id = '';
  $query1_id = '';
  $query2_id = '';
  $query3_id = '';
  $query4_id = '';
  $query5_id = '';
  $query6_id = '';
  $query7_id = '';
  $query8_id = '';
  $query9_id = '';
  $query10_id = '';
 }
 echo $error;
}?>

<!DOCTYPE html>
 <head>
  <title>Chatbot Comparison Survey</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <style>  
            #leftbox { 
                float:left;  
                width:45%; 
            } 
            #middlebox{ 
                float:left;  
                background:Green; 
                width:50%; 
            } 
            #rightbox{ 
                float:right; 
                width:45%;  
            } 
        </style>  
 </head>
 <body>
  <br />
  <div class="container">
   <h2 align="center" style="font-family:courier;">Chatbot Comparison Survey</h2>
   <br />
   <div class="col-md-6" style="margin:0 auto; float:none;">
    <form method="post">
     <label align="justify" style="background-color:LightGray; font-family:verdana;">In the following, you will see a set of queries and their responses of different chatbots. Please give a score to each of these responses between 1 - 5 ( 1 = if you like it the least, 5 = if you like it the most)</label><br>

     <br />
     <label align="justify" style="background-color:LightGray; font-family:verdana;">NOTE: Please do give the rating on the basis of the content of results, not on the illustration or aesthetics.</label><br><br/>
'''

def append_initial(users, areastat_queries, fake_queries, google_queries, faq_queries):
  for i in range(len(users)):
    with open('user_{}.php'.format(users[i]) , 'a+') as ui:
      ui.write(php_code)
      ui.write(var.format(users[i], 'areastat_{}'.format((i)%len(areastat_queries)+1), 'areastat_{}'.format((i+1)%len(areastat_queries)+1), 'fake_{}'.format((i)%len(fake_queries)+1), 'fake_{}'.format((i+1)%len(fake_queries)+1), 'fake_{}'.format((i+2)%len(fake_queries)+1), 'google_{}'.format((i)%len(google_queries)+1), 'google_{}'.format((i+1)%len(google_queries)+1), 'google_{}'.format((i+2)%len(google_queries)+1), 'faq_{}'.format((i)%len(faq_queries)+1), 'faq_{}'.format((i+1)%len(faq_queries)+1)))
      ui.write(A)

append_initial(users, areastat_queries, fake_queries, google_queries, faq_queries)     

def generate_area(users, queries):
  for i in range(len(users)):
    with open('user_{}.php'.format(users[i]) , 'a+') as ui:
      ui.write(areastat_temp.format(queries[(i)%len(queries)], '{}1.png'.format((i)%len(queries)+1), '{}2.png'.format((i)%len(queries)+1)))
      ui.write(common_temp.format(1,1,1,1,1,2,2,2,2,2))
      ui.write(areastat_temp.format(queries[(i+1)%len(queries)], '{}1.png'.format((i+1)%len(queries)+1), '{}2.png'.format((i+1)%len(queries)+1)))
      ui.write(common_temp.format(3,3,3,3,3,4,4,4,4,4))
      ui.close()
generate_area(users, areastat_queries)

def generate_fake(users, queries, subheadings):
  for i in range(len(users)):
    with open('user_{}.php'.format(users[i]) , 'a+') as ui:
      ui.write(fake_temp.format(queries[(i)%len(queries)], subheadings[(i)%len(subheadings)], '{}1.png'.format((i)%len(queries)+1), '{}2.png'.format((i)%len(queries)+1)))
      ui.write(common_temp.format(5,5,5,5,5,6,6,6,6,6))
      ui.write(fake_temp.format(queries[(i+1)%len(queries)], subheadings[(i+1)%len(subheadings)], '{}1.png'.format((i+1)%len(queries)+1), '{}2.png'.format((i+1)%len(queries)+1)))
      ui.write(common_temp.format(7,7,7,7,7,8,8,8,8,8))
      ui.write(fake_temp.format(queries[(i+2)%len(queries)], subheadings[(i+2)%len(subheadings)], '{}1.png'.format((i+2)%len(queries)+1), '{}2.png'.format((i+2)%len(queries)+1)))
      ui.write(common_temp.format(9,9,9,9,9,10,10,10,10,10))
      ui.close()

generate_fake(users, fake_queries, fake_subheadings)

def generate_google(users, queries, subheadings):
  for i in range(len(users)):
    with open('user_{}.php'.format(users[i]) , 'a+') as ui:
      ui.write(google_temp.format(queries[(i)%len(queries)], subheadings[(i)%len(subheadings)], '{}1.png'.format((i)%len(queries)+1), '{}2.png'.format((i)%len(queries)+1)))
      ui.write(common_temp.format(11,11,11,11,11,12,12,12,12,12))
      ui.write(google_temp.format(queries[(i+1)%len(queries)], subheadings[(i+1)%len(subheadings)], '{}1.png'.format((i+1)%len(queries)+1), '{}2.png'.format((i+1)%len(queries)+1)))
      ui.write(common_temp.format(13,13,13,13,13,14,14,14,14,14))
      ui.write(google_temp.format(queries[(i+2)%len(queries)], subheadings[(i+2)%len(subheadings)], '{}1.png'.format((i+2)%len(queries)+1), '{}2.png'.format((i+2)%len(queries)+1)))
      ui.write(common_temp.format(15,15,15,15,15,16,16,16,16,16))
      ui.close()

generate_google(users, google_queries, google_subheadings)

def generate_faq(users, queries, subheadings):
  for i in range(len(users)):
    with open('user_{}.php'.format(users[i]) , 'a+') as ui:
      ui.write(faq_temp.format(queries[(i)%len(queries)], subheadings[(i)%len(subheadings)], '{}1.png'.format((i)%len(queries)+1), '{}2.png'.format((i)%len(queries)+1)))
      ui.write(common_temp.format(17,17,17,17,17,18,18,18,18,18))
      ui.write(faq_temp.format(queries[(i+1)%len(queries)], subheadings[(i+1)%len(subheadings)], '{}1.png'.format((i+1)%len(queries)+1), '{}2.png'.format((i+1)%len(queries)+1)))
      ui.write(common_temp.format(19,19,19,19,19,20,20,20,20,20))
      ui.write(end)
      ui.close()


generate_faq(users, faq_queries, faq_subheadings)


new_rows = zip(email, users)

with open('emails.csv', 'w', newline = '') as f:
  csv_writer = csv.writer(f)
  for row in new_rows:
    csv_writer.writerow(row)

def mail(userid,email,server_address):    
    fromaddr = "truthcheck2k20@gmail.com"  #Put your email id from which mail is to be sent
    toaddr = [email]
    msg = MIMEMultipart()    
    msg['From'] = fromaddr
    msg['To'] = ", ".join(toaddr)
    msg['Subject'] = "Chatbot Evaluation Form" 
    temp1 = "Hello,\n\nYou are receiving this message as you signed up for the survey of fact-checking chatbots. \n\nHere is your survey link: " 
    temp2 = "\n(the link is best viewed in a laptop/desktop)\n\nThe survey will take at most 2-3 minutes. Please finish it before Aug 17, 2020.\n\nThank you for your time.\nTeam Satyanweshi."
    body = temp1 + "https://swaprava.cse.iitk.ac.in/user_{}.php".format(userid) + temp2
    #--------------------------------------------------------------
    msg.attach(MIMEText(body, 'plain'))
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login("truthcheck2k20@gmail.com", "truth$check123@") #Put your email id and password
    text = msg.as_string()
    server.sendmail(fromaddr, toaddr, text)
    server.quit()
    

for j in users:
    print("Mail sent to person with user id: ",j," and email id: ", mapping[j])
    mail(j,mapping[j],server_address)
