import os
from AppCode.Config import DBConfig
from AppCode.FileHandler import FileHandler
from werkzeug.utils import secure_filename

class DocumentHandler:
    
    years = ""
    documents = ""
    isSuccess = False
    resultMessage = ""

    def View(self,request):
        year = request.args.get('year')
        stage = request.args.get('stage')
        dbconfig = DBConfig()
        connection = dbconfig.get_db_connection()

        if not connection:
            self.isSuccess = False
            return
        cursor = connection.cursor()
 
        params = []
        query = "SELECT * FROM documents WHERE 1=1"

        if year:
            query += " AND year = %s"
            params.append(year)
        if stage:
            query += " AND stage = %s"
            params.append(stage)

            
        cursor.execute(query, params)
        documentsdata = cursor.fetchall()
        print("*************")
        print(documentsdata)
        cursor.callproc("GetYear")

        # records = []
        # for result in cursor.stored_results():
        #     records = result.fetchall()

        yearsdata = ""
        for res in cursor.stored_results():
            yearsdata = res.fetchall()
        print(yearsdata)

        self.years = yearsdata
        self.documents = documentsdata
        self.isSuccess = True

        print("document --",documentsdata)

        cursor.close()
        connection.close()


    def Upload(self, request):
        """Log user actions with timestamp, user, action, and details."""
        
        dbconfig = DBConfig()
        connection = dbconfig.get_db_connection()

        if connection:
            cursor = connection.cursor()
            files = request.files.getlist('documents')
            year = request.form['year']
            stage = request.form['stage']
            
            for file in files:
                if file is not FileHandler.ALLOWED_EXTENSIONS:
                    continue


                filename = secure_filename(file.filename)
                filepath = os.path.join(FileHandler.UPLOAD_FOLDER, filename)
                extension = file.filename.rsplit('.', 1)[1]
                # Need to Check whetehr all three items are required

                file.save(filepath)

                # cursor.execute("""
                #     INSERT INTO documents (filename, filepath, filetype, year, stage)
                #     VALUES (%s, %s, %s, %s, %s)
                # """, (filename, filepath, file.filename.rsplit('.', 1)[1], year, stage))


                cursor.callproc('InsertDocument', [
                    filename,
                    filepath,
                    extension,
                    year,
                    stage
                ])

            connection.commit()
            cursor.close()
            connection.close()
        # return redirect(url_for('view_documents'))

    #return render_template('upload.html')







# old itr report code 
@app.route('/itr_report', methods=['GET'])
def itr_report():
    yearGetter = YearGet()
    
    connection = pymysql.connect(**db_config)
    try:
        selected_year = request.args.get('year')

        if selected_year:
            # Fetch ITR data for the selected year
            query = "SELECT * FROM itr WHERE year = %s"
            df = pd.read_sql(query, connection, params=[selected_year])

            if df.empty:
                return "No records found for the selected year."

            # Transpose DataFrame: vertical fields, horizontal records
            df_transposed = df.transpose()
            df_transposed.insert(0, 'Field', df_transposed.index)

            # Rename columns as Record 1, Record 2, etc.
            record_cols = {i: f'Record {i}' for i in df_transposed.columns if isinstance(i, int)}
            df_transposed.rename(columns=record_cols, inplace=True)
            df_transposed.reset_index(drop=True, inplace=True)

            output = io.BytesIO()
            with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
                df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')

                # Format for better readability (optional)
                workbook = writer.book
                worksheet = writer.sheets['ITR_Vertical']
                worksheet.set_column(0, 0, 30)  # Field column wider

            output.seek(0)
            return send_file(
                output,
                mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                as_attachment=True,
                download_name=f"ITR_Report_{selected_year}.xlsx"
            )

        else:
            # Render dropdown form with available years
            with connection.cursor() as cursor:
                cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC")
                years = [row[0] for row in cursor.fetchall()]
            return render_template("itr_reports.html", years=years)

    finally:
        connection.close()



# --------------\

@app.route('/itr_report', methods=['GET'])
def itr_report():
    yearGetter = YearGet()


    selected_year = request.args.get('year')

    if selected_year:
            # Fetch ITR data for the selected year
        query = "SELECT * FROM itr WHERE year = %s"
        df = pd.read_sql(query, connection, params=[selected_year])

        if df.empty:
            return "No records found for the selected year."
            
          

        # Transpose DataFrame: vertical fields, horizontal records
        df_transposed = df.transpose()
        df_transposed.insert(0, 'Field', df_transposed.index)

        # Rename columns as Record 1, Record 2, etc.
        record_cols = {i: f'Record {i}' for i in df_transposed.columns if isinstance(i, int)}
        df_transposed.rename(columns=record_cols, inplace=True)
        df_transposed.reset_index(drop=True, inplace=True)

        output = io.BytesIO()
        with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
            df_transposed.to_excel(writer, index=False, sheet_name='ITR_Vertical')

            # Format for better readability (optional)
            workbook = writer.book
            worksheet = writer.sheets['ITR_Vertical']
            worksheet.set_column(0, 0, 30)  # Field column wider

        output.seek(0)
        return send_file(
                output,
                mimetype='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                as_attachment=True,
                download_name=f"ITR_Report_{selected_year}.xlsx"
            )

    else:
            # Render dropdown form with available years
        with connection.cursor() as cursor:
                # cursor.execute("SELECT DISTINCT year FROM itr ORDER BY year DESC")
                # years = [row[0] for row in cursor.fetchall()]

            years = yearGetter.get_year_by_model("GetITRYears") 
            yearGetter.close()

            print("---- year --",years)


        return render_template("itr_reports.html", years=years)
