from flask import Flask, render_template, request, redirect, url_for,jsonify
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import os
from dataFetch import fetchRate
from dataFetch2 import fetchData
from dotenv import load_dotenv
load_dotenv()
app = Flask(__name__)

#I have tried adding notes on whatever needs attention as much as I could... I know this isn't much but the APIs created work 
#and you need to setup the login and payment mechanism and display the data retrived from the other websites  on our website
#here are the links to the website: https://iunlocker.com/check_icloud.php and https://eimei24.com


app.config['SQLALCHEMY_DATABASE_URI'] = os.getenv('DATABASE_URI')
# app.config['SQLALCHEMY_DATABASE_URI']='mysql://IMEIcheck:admin@localhost/IMEIdb'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False

db = SQLAlchemy(app)

# Define User model
class User(db.Model):
    UserID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    Username = db.Column(db.String(255), nullable=False)
    EmailID = db.Column(db.String(255), nullable=False, unique=True)
    Password = db.Column(db.String(255), nullable=False)
    Premium = db.Column(db.Boolean, default=False)

# Define AdminInfo model
class AdminInfo(db.Model):
    AdminID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    SiteVisits = db.Column(db.Integer, nullable=False)
    IMEIChecks = db.Column(db.Integer, nullable=False)
    Date = db.Column(db.Date, default=datetime.now().date(), nullable=False)

# Define UserSearchHistory model
class UserSearchHistory(db.Model):
    SearchID = db.Column(db.Integer, primary_key=True, autoincrement=True)
    UserID = db.Column(db.Integer, db.ForeignKey('user.UserID'), nullable=False)
    IMEISearchStatus = db.Column(db.String(255), nullable=False)
    Date = db.Column(db.Date, default=datetime.now().date(), nullable=False)
    Timestamp = db.Column(db.TIMESTAMP, default=datetime.now(), nullable=False)

# # Note: Create tables in the database inside the application context
# with app.app_context():
#     db.create_all()
# Use the add_user function in your main app
# Sample route for adding a user (you can modify as needed)
@app.route('/add_user', methods=['GET', 'POST'])
def add_user():
    if request.method == 'POST':
        # Get user input from the form
        username = request.form.get('username')
        email = request.form.get('email')
        password = request.form.get('password')
        premium = request.form.get('premium') == 'on'  # Check if premium checkbox is checked

        # Create a new user instance
        new_user = User(Username=username, EmailID=email, Password=password, Premium=premium)

        # Add the user to the database
        db.session.add(new_user)
        db.session.commit()

        return f"User {username} added successfully!"

    return render_template('add_user.html')  

@app.route('/fetchData', methods=['GET','POST'])
def getdata():
    if request.method == 'POST':
        imei=request.form.get('IMEI')
        imeiData=fetchData(imei)
        phoneData=fetchRate(imei)   #returns just 1 for the first 2 times it is called, but works perfectly after that[Find a workaround for this]    
        
        # imeiData consists a list [imeiNumber, findMyiPhone status, iCloudStatus, website name]
        # phoneData consists a dictionary with keys as follows:
                ## {IMEI, Model, SKU, Blacklist Status, date of checking, batteryScore, display_screenScore,speeedScore, overallScore}
                ## the scores are out of 5 
        # Constructing the response
        response_data = {
            'imeiData': imeiData,
            'phoneData': phoneData
        }
        return jsonify(response_data)    #check if phoneData has been recieved on the client side itself, if not display could not receive
                                         #just print 'could not receive data'
        
        
            






if __name__ == '__main__':
    app.run(debug=True)
